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:
index.ts914 chars37 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