为什么node.js http在没有数据监听器时不会调用end事件?

mri*_*z_p 3 http node.js

我将数据从文件发送到服务器作为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)

这是一个错误吗?这是预期的行为吗?我是否在创建请求或从文件中读取数据时出错?

jil*_*lro 6

这是预期的行为.

http://nodejs.org/api/stream.html#stream_event_end

事件:'结束'

如果不再提供数据,则会触发此事件.

请注意,除非数据被完全消耗,否则不会触发结束事件.这可以通过切换到流动模式,或通过重复调用read()直到结束来完成.

来自doc: