node.js`response.end`事件是否会发送可选的`data`和`encoding`参数?

时间:2016-04-16 16:42:24

标签: javascript node.js event-handling

文档定义response.end([data][, encoding][, callback]),并声明:

  

如果指定了数据,则相当于调用response.write(data,   编码)后跟response.end(回调)。

我是否正确使用end事件,或者是否有人会将数据传递到end事件?

var http = require('http');

http.get(
    process.argv[2],
    function (response) {
        response.setEncoding('utf8');
        response.on('error', console.error);
        response.on('data', console.log);

        // Check for data and exit on 'end' event
        response.on(
            'end',
            function (data, encoding) {
                if ( null != data ) {
                    console.log(data.toString(encoding));
                }
                return;
            }
        );
    }
);

1 个答案:

答案 0 :(得分:0)

response.on('end'...)表示响应中没有更多数据。

如文档中所述,data以块的形式发送。它是一个可读的流,on('end')允许您传入您自己的数据,您可以在那里有简单的文本,这就是这样写的:

文档基本上解释了两种方法。

示例:

response.write('Hello World\n');
response.end();

OR
response.end('Hello World\n');

一般来说,这适用于少量数据,但数据的分块是在response.on('data'...);中处理的,您可以将数据放入数组中,然后将该数组传递给{ {1}}这就是我建议为更大的分块数据做这件事的方法。一个很好的练习可能是在回调中记录数据以查看它。

编辑:

在评论中提出您的问题:

你的代码是正确的,可选的,以这种方式思考,你向该函数发送一些东西,一个请求,它做一个响应,如果它的大块被分成块,那么你可以在{{{{{{{ 1}},你可以使用response.on('end'...)在最后发送回来,简单就是那个

希望有所帮助。