假设我在Node.js中使用http.request
向服务器发送HTTP请求,但我唯一感兴趣的是状态代码 - 看它是否有效。我明确 NOT 感兴趣的是响应流。
所以,基本上我的代码看起来像这样:
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();
或类似的东西,以确保流关闭和垃圾收集正确?有什么需要注意的吗?
答案 0 :(得分:0)
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('data\n');
req.write('data\n');
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
请参阅上面的链接以获取信息,以了解为何现在需要这样做。