假设我在 Node.js 中使用 http.request
向服务器发送 HTTP 请求,但我唯一感兴趣的是状态代码 - 看看它是否有效。我明确不感兴趣的是响应流。
所以,基本上我的代码看起来像这样:
var req = https.request(options, {
method: 'POST',
path: '/'
}), function (res) {
// Handle res.statusCode
callback(null);
});
req.write('Some data ...');
req.end();
我现在的问题是我是否必须对res
流执行任何操作:我是否必须阅读它,关闭它,...?
我是否需要以下内容:
res.end();
或
res.resume();
或类似的东西,以确保关闭流并正确收集垃圾?有什么需要注意的吗?
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
//You do not have to write this listener if you don't want to
//but NOde will still get all the chunks of data, and attempt to
//call a callback it will find null, and end up discarding every "chunk"
});
res.resume();//Omitting the above(empty ondata listener) and including this line, would exhibit almost identical behavior, res.resume() being very slightly more performant.
//Not there is no res.end(), even in the version that is processing data
//Calling end() is the job of the sender, not the receiver
});
// write data to request body
req.write('datan');
req.write('datan');
req.end();
//req.end() signifies the end of the data that you are writing to the
//responding computer.
http://www.infoq.com/news/2013/01/new-streaming-api-node
请参阅上面的链接以获取有关为什么现在需要这样做的参考信息。