return a binary response from a http server in javascript

To return a binary response from a HTTP server in Node.js, you can use the built-in http module. Here's an example code snippet:

index.tsx
const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  // Read the binary file
  const binaryData = fs.readFileSync('path/to/file');
  
  // Set response headers
  res.setHeader('Content-Type', 'application/octet-stream');
  res.setHeader('Content-Disposition', 'attachment; filename="file.bin"');
  
  // Write the binary data to the response
  res.write(binaryData, 'binary');

  // End the response
  res.end();
});

server.listen(8080, () => {
  console.log('Server running on port 8080');
});
551 chars
22 lines

In the example above, we create a HTTP server using http.createServer. Inside the server's request listener function, we read the binary data from a file using fs.readFileSync. Then, we set the appropriate response headers using res.setHeader. Lastly, we write the binary data to the response using res.write with the 'binary' encoding parameter and end the response using res.end.

Note that we set the 'Content-Type' header to 'application/octet-stream', which is a generic binary data-type, and the 'Content-Disposition' header with the value attachment; filename="file.bin" to force the browser to download the binary file with the name file.bin.

gistlibby LogSnag