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.