make a http request with a custom body as binary and return a binary response in typescript

To make a http request with a custom body as binary and return a binary response in Typescript, you can use the http module and Buffer class that come with Node.js.

Here's an example of how to do it:

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

// create a new http request
const req = http.request({
    method: 'POST',
    hostname: 'example.com',
    path: '/api',
    headers: {
        // tell the server that we're sending binary data
        'Content-Type': 'application/octet-stream',
        // set the binary data length
        'Content-Length': binaryData.length
    }
}, (res) => {
    let responseData: Buffer[] = [];

    // accumulate the response data
    res.on('data', (chunk) => {
        responseData.push(chunk);
    });

    // when the response is complete
    res.on('end', () => {
        // join all the response data chunks into a single Buffer
        const responseBody = Buffer.concat(responseData);

        // do something with the response body
        console.log(responseBody);
    });
});

// send the binary data in the request body
req.write(binaryData);

// end the request
req.end();
911 chars
37 lines

In this example, we're creating a new http request using the http.request() method. We specify the request method, hostname, path, and headers. In this case, we're telling the server that we're sending binary data by setting the Content-Type header to application/octet-stream and setting the Content-Length header to the length of the binary data.

We then set up event listeners to accumulate the response data as it comes in. Once the response is complete, we join all the response data chunks into a single Buffer using Buffer.concat(). We can then do something with the response body.

Finally, we send the binary data in the request body using the req.write() method and end the request using req.end().

gistlibby LogSnag