Windows 7/10,
node 5.6.0, and latest builds...
This seems like something fairly critical...
"use strict";
const fs = require( 'fs' );
var outData = fs.createWriteStream( "output.txt" );
outData.write( "line one" );
outData.write( "line two" );
outData.close();
results in a file that only has 'line one' in it.
it can be several lines... I'm often missing 5 lines in this one file... but basically every file never writes all information to the file.
this might be similar to https://github.com/nodejs/node/pull/2314
Here is a working example. In order to have a guarantee that write() has finished, you must wait for the callback on it.
'use strict'
const fs = require('fs')
const stream = fs.createWriteStream('out.txt')
stream.write('line one', () => {
stream.write('line two', () => {
stream.close()
})
})
Okay I started to dig into the code, and added some console.log( stream ); after the writes.... there's a 'pendingcb' which goes up, and things start to get buffered... so I supposed maybe if there wasn't a callback it would fail.
It will take some time to restructure the code to fit HAVING to use the callbacks.
I would still think that close operation should pend itself after the writes, or mark the stream as closed so the last write can complete the close....
but even in a more complex case where I continue on to do other work with other files for a long amount of time the output still doesn't go... so the pending writes apparently never get called without having a callback of some sort...
@d3x0r , maybe you are looking for WritableStream#end() ? That will automatically handle closing the stream for you after pending writes are done.
Note that close() is not part of the public API (https://nodejs.org/api/stream.html#stream_class_stream_writable)
I had added
outData.write( "line two" );
outData.end();
outData.close();
but that made no difference.
This works as expected. close immediately closes fd without flushing ending writes. Just call end and fd will be closed automatically after writes are flushed.
confirmed; replacing close with end lets it work :)
close() is no longer a method on the writable instance, use end() instead
Most helpful comment
Here is a working example. In order to have a guarantee that
write()has finished, you must wait for the callback on it.