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

我有几个Express应用程序,并且我看到在某些模块中, 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(); }); 

这两种情况都有效,但是当我运行很多请求时,我担心泄漏或者文件描述符或者类似的东西。 哪一个更“正确”?

你的问题的答案是否定的。 如果调用res.send()则不必调用res.end() res.send()res.send()为你调用res.end()

取自/lib/response.js ,这里是res.send()函数的结尾:

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

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

结束响应过程。 这个方法实际上来自Node核心 ,特别response.end() method of http.ServerResponse.response.end() method of http.ServerResponse. 用于快速结束没有任何数据的响应。

如果您需要使用数据进行响应,请使用res.send() and res.json().

你必须调用end()函数的一个例子是当你发送缓冲区作为一个文件下载。

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