21

I have a binary data(like image file) in Buffer object(not file), and want to serve the raw binary data to client through http.ServerResponse. How can I do it ?

3
  • Could you please make clear why the question is downvoted, if possible ? Commented Dec 21, 2015 at 9:01
  • I don't know why it is downvoted, but I was looking through Node's Response.js source and API, and I logged its keys, but I could not find a write method. What is the write method? Where did you learn of it? Commented Jul 11, 2016 at 19:08
  • The method is well documented in node js docs you can also find an explanation in the classic w3schools Commented Jun 15, 2020 at 1:38

2 Answers 2

36

I managed to find out the answer. Just add "binary" encoding to both write() and end().

    res.write(buffer,'binary');
    res.end(null, 'binary');

Note that both "write" and "end" function requires the 'binary' encoding specified. Otherwise, the buffer is encoded as UTF-8. (So, JPEG header "ff d8 ff e0" will be "c3 bf c3 98 c3 bf c3 a0"...)

Sign up to request clarification or add additional context in comments.

Comments

0

Using Axios for fetch the Binary data and send as Image

app.get(url, async (req, res) => {
  let { thread, blob } = req.params;
  try {
    let { data, body, headers } = await axios.get(...);
    res.end(data);
  } catch (e) {
    console.log("e", e);
    res.send("error");
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.