Categories
JavaScript Answers

How to overwrite a file using fs in Node.js?

Spread the love

Sometimes, we want to overwrite a file using fs in Node.js.

In this article, we’ll look at how to overwrite a file using fs in Node.js.

How to overwrite a file using fs in Node.js?

To overwrite a file using fs in Node.js, we can call writeFile or writeFileSync with the 'w' flag.

For instance, we write

fs.writeFileSync(path, content, {
  encoding: 'utf8',
  flag: 'w'
})

to call writeFileSync with the file path, file content, and the 'w' flag to write the file even if it already exists.

We can pass in the same arguments with writeFile to write the file asynchronously.

Conclusion

To overwrite a file using fs in Node.js, we can call writeFile or writeFileSync with the 'w' flag.

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 *