Categories
JavaScript Answers

How to fix Node fs.createWriteStream does not immediately create file?

Spread the love

To fix Node fs.createWriteStream does not immediately create file, we call write to write the file content.

For instance, we write

const tempFile = fs.createWriteStream(tempFilepath);

tempFile.on("open", (fd) => {
  http.request(url, (res) => {
    res
      .on("data", (chunk) => {
        tempFile.write(chunk);
      })
      .on("end", () => {
        tempFile.end();
        fs.renameSync(tempFile.path, filepath);
        return callback(filepath);
      });
  });
});

to create the tempFile write stream with createWriteStream.

And then we call res.on to listen for the data event to get the data.

We call tempFile.write with chunk to write the chunk to the write stream.

And we call tempFile.end to stop writing when the end event is emitted, which happens when all the data is received.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.