是否必须用 node.js 快速调用 res.end() ?

我有几个 特快应用程序,我看到在一些模块中,res.end()在请求处理程序的末尾(在 res.sendres.json之后)被调用,而在其他模块中,它没有被调用。

例如:

app.get('/test', function(req, res) {
res.send('Test', 200);
});

或:

app.get('/test', function(req, res) {
res.send('Test', 200);
res.end();
});

这两种情况都可以工作,但是当我运行许多请求时,我担心会出现泄漏或者文件描述符不足之类的情况。哪个更正确?

61297 次浏览

The answer to your question is no. You don't have to call res.end() if you call res.send(). res.send() calls res.end() for you.

Taken from /lib/response.js, here is the end of the res.send() function:

  //. . .
// respond
this.end(head ? null : body);
return this;
}

res.end([data] [, encoding])

Ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse. Use to quickly end the response without any data.

If you need to respond with data, instead use methods such as res.send() and res.json().

one example where you must call end() function is when you send buffer as a file to download.

res.write(buffer);
res.end();