Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

stream - event associated with fs.createWriteStream in node.js

What event is triggered when EOF is reached while writing to a stream ? My code is as follows. and it is as per http://docs.nodejitsu.com/articles/advanced/streams/how-to-use-fs-create-write-stream

But surprisingly my 'end' event is never fired. When I checked http://nodejs.org/api/stream.html#stream_event_end, I see that writable stream does not have any event on '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);
}

How do I capture the EOF event ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Updated 30 Oct 2013

Readable Steams emit close event when the underlying resource done writing.

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

But if you want to catch the moment when fs finished writing data to the disc, you need 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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...