make a http request with a custom body as binary in typescript

To make a HTTP request with a custom binary body in TypeScript, you can use the http module in Node.js. The following code demonstrates how to make a POST request with a binary body:

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

const options = {
  hostname: 'example.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/octet-stream', // specify the content type as binary
    'Content-Length': Buffer.byteLength(binaryData) // set the length of the binary data
  }
};

const binaryData = Buffer.from('your-binary-data-here');

const req = http.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (error) => {
  console.error(error);
});

// write the binary data to the request body
req.write(binaryData);
req.end();
676 chars
31 lines

This code creates a new request with http.request() and sets the method to POST. It also sets the Content-Type header to application/octet-stream to specify that the body is binary data, and sets the Content-Length header to the length of the binary data. Finally, it writes the binary data to the request body with req.write() and ends the request with req.end().

gistlibby LogSnag