2012-10-31 33 views
15

在寫入流時到達EOF時觸發了什麼事件? 我的代碼如下。這是根據http://docs.nodejitsu.com/articles/advanced/streams/how-to-use-fs-create-write-stream與node.js中的fs.createWriteStream關聯的事件

但令人驚訝的是我的'結束'事件從未被解僱。當我檢查http://nodejs.org/api/stream.html#stream_event_end,我看到寫流沒有


var x = a1.jpg; 
var options1 = {'url': url_of_an_image, 'encoding': null}; 
var r = request(options1).pipe(fs.createWriteStream('/tmp/imageresize/'+x)); 

r.on('end', function(){ 
    console.log('file downloaded to ', '/tmp/imageresize/'+x); 
} 

如何捕獲EOF事件上「結束」無論如何?

回答

48

更新2013年10月30日

可讀蒸emit close event when the underlying resource done writing

r.on('close', function(){ 
    console.log('request finished downloading file'); 
}); 

但是,如果你想趕上那一刻fs寫完數據刻錄到光盤,你需要Writeable Stream finish event

var w = fs.createWriteStream('/tmp/imageresize/'+x); 

request(options1).pipe(w); 

w.on('finish', function(){ 
    console.log('file downloaded to ', '/tmp/imageresize/'+x); 
}); 
+0

感謝獅子座。讓我試試看!將盡快更新。 – user644745

+0

是的。它正在工作。再次感謝。 – user644745

+0

關閉事件是否意味着所有內容都已刷新到磁盤或者它是否仍在OS寫入緩衝區中?什麼時候可以安全退出流程? – BHP