In trying to write to and then read from the same file, I’ve noticed that the below approach does not work, and I’d like to understand why (I suspect I’m missing some subtleties of async
/await
and stream
constructs). In running the code below, FileA
is written to disk correctly, but readTextFile
prints ['']
, as would be expected if FileA
were empty. It feels like the output of createTextFile()
hasn’t been flushed to disk by the time readTextFile()
is called (I would have expected await
to solve this). The example works if I make the create function synchronous:
const fs = require("fs");
const FileA = 'testfile.txt';
const createTextFile = async () => {
const rows = ['a','b','c','d'];
const outstream = fs.createWriteStream(FileA, {flush: true, autoClose: true});
for(el of rows){
outstream.write(el+'n');
}
outstream.end();
};
const readTextFile = () => {
const clist = fs.readFileSync(FileA).toString().split("n");
console.log(clist);
};
const flow = async config => {
await createTextFile();
readTextFile();
};
flow();