Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs empty file on 'finish' after pipe()

Tags:

stream

node.js

fs

I write a readable stream to a file and want to know when it is finished so I can access the file on the disk. I listen to the finish event but when I do a stat in the listener the file size is 0. After some delay the size is correct.

Is this normal behavior?

According to the docs the event is emitted when all data has been flushed to the underlying system.

var ws = fs.createWriteStream(path);
file.pipe(ws); // file is a readable stream
ws.on('finish', function() {
    try {
        stat = fs.statSync(path); // stat.size: 0
    }
    catch (err) { /*...*/ }
});
like image 271
sceid Avatar asked Aug 30 '25 15:08

sceid


1 Answers

The finish event is emitted when all data is written to the stream but file may not be closed at that time. You can listen the close event which is emitted once the file handler is closed.

ws.once('close', function() {
    try {
        stat = fs.statSync(path);
    }
    catch (err) { /*...*/ }
});
like image 107
hassansin Avatar answered Sep 02 '25 17:09

hassansin