Difference between response.send and response.write in node js

后端 未结 4 537
耶瑟儿~
耶瑟儿~ 2020-12-01 01:31

I have written a small API which uses the Node js \"restify\" framework. This API receives a request (actually anything after \"/\") and then send that request to another se

相关标签:
4条回答
  • 2020-12-01 01:44

    response.send(msg) is equal to response.write(msg);response.end();

    Which means, send can only be called once, write can be called many times, but you must call end yourself.

    0 讨论(0)
  • 2020-12-01 01:48

    I was trying to send huge text data(295mb) over http using res.send(data) and res.write(data). I noticed that res.send(data) is slower than res.write(data). I observed following things.

    res.send(data): it can be called only once and it sends data in chunk of some buffer size to client and then again comes back and sends another chunk of buffer size so there is a lot of back and forth http communication.

    res.write(data): It can be called multiple times followed by res.end() and It creates buffer size based on whole data and sends over http so it would be faster in case of huge amount of data.

    0 讨论(0)
  • 2020-12-01 01:52

    I can't find response.send() in the docs, but I assume .send() will fill in and send the response so can only be called once, whereas .write() will just write the response, but you have to send it using response.end()

    This means you can edit the headers using .write() because the response has not been sent yet.

    EDIT :

    response.send() is part of the restify Response API wrapper

    0 讨论(0)
  • 2020-12-01 02:05

    res.send() is part of Express.js instead of pure Node.js.

    Just an side observation. My app sometimes send back a very large Json object ( HighChart object that contains over 100k points). With res.send() sometimes it hangs and choke up the server, whereas res.write() and res.end() handle it just fine.

    I also noticed a memory spike when res.send() is invoked.

    0 讨论(0)
提交回复
热议问题