Node.js HTTP响应结束事件从未触发

时间:2019-03-05 12:19:30

标签: node.js http fs

有人可以告诉我为什么它从不触发结束事件吗?我如何使其可行?

代码:

const http = require('http');
const fs = require('fs');

const file = fs.createWriteStream("mqdefault.jpg");
const request = http.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg", function(response) {
    response.on('data', function(chunk){
        response.pipe(file);
        process.stdout.write('Received data\n');
    })
    response.on('end', function(){
        response.pipe(file);
        process.stdout.write('All data received');
    })
}).on('error', (e) => {
    console.error(`Got error: ${e.message}`);
});

2 个答案:

答案 0 :(得分:0)

它确实触发了结束事件

nt@nt-MS-7885:~/Desktop/node $ node index.js
Received data
Received data
All data received

您没有将所有块都添加到文件中 这样您就可以得到一个空文件

尝试使用流

const http = require('http');
const fs = require('fs');
const Stream = require('stream').Transform;

const fileName = "mqdefault.jpg";
const request = http.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg", function(response) {
    let data = new Stream()

    response.on('data', function(chunk){
        data.push(chunk);
        process.stdout.write('Received data\n');
    })
    response.on('end', function(){
        fs.writeFileSync(fileName, data.read());                               
        process.stdout.write('All data received');

    })
}).on('error', (e) => {
    console.error(`Got error: ${e.message}`);
});

答案 1 :(得分:0)

使用 file.write(chunk)代替管道。和 file.end 完成编写。

   const http = require('http');
   const fs = require('fs');

   const file = fs.createWriteStream("mqdefault.jpg");
   const request = http.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg", function(response) {
       response.on('data', function(chunk){
           file.write(chunk);
           process.stdout.write('Received data\n');
       })
       response.on('end', function(){
           file.end();
           process.stdout.write('All data received');
       })
   }).on('error', (e) => {
       console.error(`Got error: ${e.message}`);
   });