首页 > 这段node.js代码为什么会输出两次console.log的内容?

这段node.js代码为什么会输出两次console.log的内容?

下面这段代码执行之后,在终端输出两句 hello,初学node,不是很理解为什么会有这样的结果。

require('http').createServer(function(req,res){
    res.writeHead(200,{'Content-Type':'image/png'});
    var stream = require('fs').createReadStream('image.png');
    stream.on('data',function(data){
        res.write(data);
    });
    stream.on('end',function(){
        res.end();
    });
    console.log('hello');
}).listen(3000);

结果截图


估计是一次获取图片 一次获取favicon


发了两次请求把


因为data是buffer,在ondata事件里有一段段的buffer,应当在onend事件中把buffer拼接起来,注意buffer隐式转换类型的问题,不能用temp+=data,否则可能会造成乱码。


访问了两次啊,

【热门文章】
【热门文章】