我将数据从文件发送到服务器作为HTTP POST请求,如下所示:
var options = {
"hostname": "example.com",
"port": 42,
"path": "/whatever",
"method": "PUT",
"headers" : {
// a few headers
}
};
var req = http.request(options, function(res) {
res.on("end", function () {
console.log("The request is finished");
});
});
var stream = fs.createReadStream("/tmp/someFile");
stream.on("data", function(data) {
req.write(data);
});
stream.on("end", function() {
req.end();
});
Run Code Online (Sandbox Code Playgroud)
我正在倾听res.on("end"),以便在上传文件后做更多的事情.
但是,在上面的示例中,res.on("end")永远不会调用它.
令人惊讶的是,当我为data事件添加一个监听器时,res.on("end")可靠地调用.
如果我完全忽略下面示例中的数据,这甚至可以工作:
var options = {
"hostname": "example.com",
"port": 42,
"path": "/whatever",
"method": "PUT",
"headers" : {
// a few headers
}
};
var req = http.request(options, function(res) {
res.on("data", function () {
/*
* I don't even care for the data returned...
*/
});
res.on("end", function () {
console.log("The request is finished");
});
});
var stream = fs.createReadStream("/tmp/someFile");
stream.on("data", function(data) {
req.write(data);
});
stream.on("end", function() {
req.end();
});
Run Code Online (Sandbox Code Playgroud)
这是一个错误吗?这是预期的行为吗?我是否在创建请求或从文件中读取数据时出错?
这是预期的行为.
http://nodejs.org/api/stream.html#stream_event_end
事件:'结束'
如果不再提供数据,则会触发此事件.
请注意,除非数据被完全消耗,否则不会触发结束事件.这可以通过切换到流动模式,或通过重复调用read()直到结束来完成.
来自doc:
http://nodejs.org/api/http.html#http_http_request_options_callback
可选的回调参数将作为"响应"事件的一次性侦听器添加.
'响应'事件 http://nodejs.org/api/http.html#http_event_response
response参数将是http.IncomingMessage的一个实例.
http.IncomingMessage http://nodejs.org/api/http.html#http_http_incomingmessage
它实现了可读流接口.
可读流'结束'事件 http://nodejs.org/api/stream.html#stream_event_end