1

I'm quite new to javascripts. I'm using node js writable stream to write a .txt file; It works well, but I cannot understand how to properly close the file, as its content is blank as long as the program is running. More in detail I need to read from that .txt file after it has been written, but doing it this way returns an empty buffer.

let myWriteStream = fs.createWriteStream("./filepath.txt");
myWriteStream.write(stringBuffer + "\n");    
myWriteStream.on('close', () => {
           console.log('close event emitted');
    });
myWriteStream.end();

// do things..
let data = fs.readFileSync("./filepath.txt").toString().split("\n");

Seems like the event emitted by the .end() method is triggered after the file reading, causing it to be read as empty. If I put a while() to wait for the event to be triggered, so that I know for sure the stream is closed before the reading, the program waits forever. Do you have any clue of what I'm doing wrong?

jorgenkg
  • 4,140
  • 1
  • 34
  • 48
  • its a write stream not a read stream. How do you even read from it? – The Fool Feb 26 '22 at 11:47
  • I use the writestream to write the .txt, then I use `fs.readFileSync("./filepath.txt")` to read from .txt. @TheFool – aka.Calamaro Feb 26 '22 at 12:28
  • Your code is working, as expected. At least for me. https://replit.com/@bluebrown/WingedSpeedyMp3#index.js – The Fool Feb 26 '22 at 12:40
  • Note that `write()` and `end()` are async functions that accept a callback that is called upon completion. In this snippet, nothing keeps the process from immediately reading the file before the file has been written. The snippet closes the file correctly, but as it stands, it may read the file before flushing the write buffer. – jorgenkg Feb 26 '22 at 15:40

1 Answers1

1

your missing 2 things one test that write is succeed then you need to wait for stream finish event

const { readFileSync, createWriteStream } = require('fs')

const stringBuffer = Buffer.from(readFileSync('index.js')
)
const filePath = "./filepath.txt"
const myWriteStream = createWriteStream(filePath)

let backPressureTest = false;
while (!backPressureTest) {
    backPressureTest = myWriteStream.write(stringBuffer + "\n");
}
myWriteStream.on('close', () => {
    console.log('close event emitted');
});
myWriteStream.on('finish', () => {
    console.log('finish event emitted');
    let data = readFileSync(filePath).toString().split("\n");
    console.log(data);
});

myWriteStream.end();
Naor Tedgi
  • 5,204
  • 3
  • 21
  • 48