callback来处理pipe道的完成

我正在使用下面的node.js代码从某个url下载文件并将其保存在磁盘中。 我想知道下载文档的时间。 我还没有看到任何callbackpipe.Or,是否有任何“结束”事件,可以捕获完成下载?

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

stream是EventEmitter的,所以你可以听某些事件。 如你所说有一个finish事件的请求(以前end )。

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

有关哪些事件可用的更多信息,可以查看stream文档页面 。

基于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(){ ... }); 

代码片段,用于通过http(s)将内容从pipe道传输到文件系统。 由于@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); }); 

我发现我的问题有点不同的解决scheme。 思想值得分享。

大部分示例readStreams从文件中创buildreadStreams 。 但在我的情况下, readStream必须从来自消息池的JSONstring创build。

 var jsonStream = through2.obj(function(chunk, encoding, callback) { this.push(JSON.stringify(chunk, null, 4) + '\n'); callback(); }); // message.vale --> valeu/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 );