Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to fix fs.createWriteStream does not immediately create file in Node.js.

In this article, we’ll look at how to fix fs.createWriteStream does not immediately create file in Node.js.

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

To fix fs.createWriteStream does not immediately create file in Node.js, we shold get the file from the 'open' event callback.

For instance, we write

const tempFile = fs.createWriteStream(tempFilePath);
tempFile.on("open", (fd) => {
  //...
});

to call fs.createWriteStream with the tempFilePath to create a write stream to write to the file at tempFilePath.

Then we call tempFile.on with 'open' to listen to the 'open' event which is triggered when the write stream is opened.

And then we can do whatever we want with the file inside.

Conclusion

To fix fs.createWriteStream does not immediately create file in Node.js, we shold get the file from the 'open' event callback.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *