create a http server and read the request body as binary and return a binary response in typescript

To create a HTTP server in Node.js using TypeScript, we’ll need to use the built-in ‘http’ module. We’ll create a function that takes two parameters, the request and the response. When the server receives a request, it passes it to our function.

We can read the request body as binary data using a Buffer object, and then convert it into the format we need. Similarly, we can construct a binary response using a Buffer object and write it to the response.

Here's the sample implementation:

import * as http from 'http';

function binaryRequestHandler(
  req: http.IncomingMessage,
  res: http.ServerResponse
) {
  if (req.method === 'POST') {
    const chunks: any[] = [];

    req.on('data', chunk => {

    req.on('end', () => {
      const binaryData = Buffer.concat(chunks);
      // do something with binaryData

      // send binary response
      const responseBuffer = Buffer.from('binary response data here', 'binary');
      res.writeHead(200, {
        'Content-Type': 'application/octet-stream',
        'Content-Length': responseBuffer.length

  } else {
    res.writeHead(405, { 'Content-Type': 'text/plain' });
    res.end('Method Not Allowed');

const port: number = 3000;
http.createServer(binaryRequestHandler).listen(port, () => {
  console.log(`Binary HTTP server running on port ${port}`);
914 chars
37 lines

In the above code, we’ve created a simple HTTP server that listens for incoming binary requests through the POST method. When a request is received, we read its binary data into a Buffer object and perform the operations we want on the data. After that, we create a binary response using a Buffer object and send it back to the client as an application/octet-stream content type.

Note that we're concatenating the chunks of data streamed through on('data') event into a single Buffer object, and once all data have been received, we perform our operations.

Overall, reading binary data from requests and sending binary responses in Node.js HTTP server is similar to how we would do it in other programming languages, with the added benefit of the efficient Buffer API.

gistlibby LogSnag