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

To create an HTTP server and read the request body as binary in TypeScript, you can use the built-in http module of Node.js to handle incoming requests, and the Buffer class to read the binary data from the request body.

Here's an example code snippet that implements this functionality:

index.ts
import * as http from 'http';

const server = http.createServer((req, res) => {
   if (req.method === 'POST') {
      const chunks: Uint8Array[] = [];

      req.on('data', (chunk: Uint8Array) => {
         chunks.push(chunk);
      });

      req.on('end', () => {
         const data = Buffer.concat(chunks);
         console.log('Request data:', data);
         res.statusCode = 200;
         res.end();
      });
   } else {
      res.statusCode = 405;
      res.end();
   }
});

server.listen(8080, () => {
   console.log('Server listening on port 8080');
});
565 chars
26 lines

In this example, we create an HTTP server using the http.createServer() method and define a request listener function that checks if the incoming request method is POST. If it is, we create an empty array of Uint8Array objects to store the request body chunks. We then listen for incoming data chunks using the req.on('data', ...) event and push them to the chunks array.

When the request ends (req.on('end', ...)), we concatenate all the chunks into a single Buffer object using the Buffer.concat() method and log the binary data to the console. Finally, we send a 200 OK response to the client.

If the incoming request method is not POST, we send a 405 Method Not Allowed response to the client.

Note that in this example, we are assuming that the incoming binary data is encoded using UTF-8. If your data is encoded using a different character set, you will need to specify the encoding when creating the Buffer object.

gistlibby LogSnag