回调处理管道的完成


195

我正在使用以下node.js代码从某些url下载文档并将其保存在磁盘中。我想知道何时下载该文档。我没有看到使用pipe进行任何回调。或者,下载完成后是否可以捕获任何“结束”事件?

request(some_url_doc).pipe(fs.createWriteStream('xyz.doc'));

Answers:


301

流是,EventEmitter因此您可以听某些事件。如您所说,有一个finish请求事件(以前是end)。

 var stream = request(...).pipe(...);
 stream.on('finish', function () { ... });

有关可用的事件的更多信息,请查看流文档页面


12
var r = request(...).on("end",function(){/* CALLBACK */}).pipe(...);
Denys Vitali

6
对我来说,事件“关闭”而不是“结束”有效r.on('close'), function () {...})
Judson

9
“结束”事件现在是“结束”管道事件:nodejs.org/api/stream.html#stream_event_finish
Pier-Luc Gendreau

13
“结束”事件仍然存在,并用于可读流。可写流使用“完成”。这是因为Transform流是两者的混合,需要区分事件。
noderman '16

16
该线程很好地总结了如何使用节点流。
–'pomber


9

用于将内容从Web通过http(s)传递到文件系统的代码段。由于@starbeamrainbowlabs注意到事件finish确实起作用

var tmpFile = "/tmp/somefilename.doc";

var ws = fs.createWriteStream(tmpFile);
ws.on('finish', function() {
  // pipe done here, do something with file
});

var client = url.slice(0, 5) === 'https' ? https : http;
client.get(url, function(response) {
  return response.pipe(ws);
});

on'finish'对我有效,而'end'对我无效。谢谢!
shaosh

1
在一种特定情况下,似乎在所有预期字节到达之前都未完成处理
迈克尔

4

对于这种情况,我发现了一些不同的解决方案。值得分享的思想。

大多数示例readStreams从文件创建。但就我而言readStream,必须JSON从消息池中的字符串创建。

var jsonStream = through2.obj(function(chunk, encoding, callback) {
                    this.push(JSON.stringify(chunk, null, 4) + '\n');
                    callback();
                });
// message.value --> value/text to write in write.txt 
jsonStream.write(JSON.parse(message.value));
var writeStream = sftp.createWriteStream("/path/to/write/write.txt");

//"close" event didn't work for me!
writeStream.on( 'close', function () {
    console.log( "- done!" );
    sftp.end();
    }
);

//"finish" event didn't work for me either!
writeStream.on( 'close', function () {
    console.log( "- done!"
        sftp.end();
        }
);

// finally this worked for me!
jsonStream.on('data', function(data) {
    var toString = Object.prototype.toString.call(data);
    console.log('type of data:', toString);
    console.log( "- file transferred" );
});

jsonStream.pipe( writeStream );

您没有监听“完成”,而是有两个“关闭”处理程序,也许就是这个原因。“完成”事件对我有用。
jowo

3

这是一种处理请求中的错误并在写入文件后调用回调的解决方案:

request(opts)
    .on('error', function(err){ return callback(err)})
    .pipe(fs.createWriteStream(filename))
    .on('finish', function (err) {
        return callback(err);
    });
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.