I am a beginner to express.js
and I am trying to understand the difference between res.send
and res.write
?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
res.send
- res.send is only in Express js.
- Performs many useful tasks for simple non-streaming responses.
- Ability to automatically assigns the Content-Length HTTP response header field.
- Ability to provides automatic HEAD & HTTP cache freshness support.
Practical explanation
res.send
can only be called once, since it is equivalent tores.write
+res.end()
Example
app.get('/user/:id', function (req, res) { res.send('OK'); });
for more details expressjs.com/en/api.html
res.write
- Can be called multiple times to provide successive parts of the body.
Example
response.write('<html>'); response.write('<body>'); response.write('<h1>Hello, World!</h1>'); response.write('</body>'); response.write('</html>'); response.end();
For more details
nodejs.org/docs
nodejs.org/en/docs/guides
回答2:
res.send
is equivalent to res.write + res.end
So the key difference is res.send
can be called only once where as res.write
can be called multiple times followed by a res.end
.
But apart from that res.send
is part of Express. It can automatically detect the length of response header.
But there may be be a chance of memory spike with res.send(), in case of large files, our application hangs in between .