Answers:
流是,EventEmitter因此您可以听某些事件。如您所说,有一个finish请求事件(以前是end)。
var stream = request(...).pipe(...);
stream.on('finish', function () { ... });
有关可用的事件的更多信息,请查看流文档页面。
r.on('close'), function () {...})
基于nodejs文档http://nodejs.org/api/stream.html#stream_event_finish,它应该处理writableStream的finish事件。
var writable = getWriteable();
var readable = getReadable();
readable.pipe(writable);
writable.on('finish', function(){ ... });
用于将内容从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);
});
对于这种情况,我发现了一些不同的解决方案。值得分享的思想。
大多数示例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 );
var r = request(...).on("end",function(){/* CALLBACK */}).pipe(...);