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.ts565 chars26 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