javascript - Node: fs write() doesn't write inside loop. Why not? -
i want create write stream , write data comes in. however, able create file nothing written it. eventually, process runs out of memory.
the problem, i've discovered i'm calling write() whilst inside loop.
here's simple example:
'use strict' var fs = require('fs'); var wstream = fs.createwritestream('myoutput.txt'); (var = 0; < 10000000000; i++) { wstream.write(i+'\n'); } console.log('end!') wstream.end();
nothing ever gets written, not hello. why? how can write file within loop?
the problem aren't ever giving chance drain buffer. buffer gets full , run out of memory.
writestream.write
returns boolean value indicating if data written disk. if data not written, should wait drain
event, indicates buffer has been drained.
here's 1 way of writing code utilizes return value of write
, drain
event:
'use strict' var fs = require('fs'); var wstream = fs.createwritestream('myoutput.txt'); function writetostream(i) { (; < 10000000000; i++) { if (!wstream.write(i + '\n')) { // wait drain start writing data left off wstream.once('drain', function() { writetostream(i + 1); }); return; } } console.log('end!') wstream.end(); } writetostream(0);