I'm trying to overwrite an existing file. I'm first checking if the file exists using:
fs.existsSync(path)
If file does not exit I'm creating and writing using:
fs.writeFileSync(path,string)
The problem is when the file already exists and I want to over write all its contents. Is there a single line solution, so far I searched and found solutions that use fs.truncate & fs.write, but is there a one hit solution?
nodejs's fs. rename() overwrites files because that is how the Unix rename() is defined and fs.
Use fs. unlink() method to delete an existing file.
The simplest way, and often the most appropriate, is to use the writeFile method in the fs module. This allows you to write to a specified file path, with asynchronous behavior, and creates a new file or replaces one if it exists at the path.
js provides an inbuilt module called FS (File System). Node. js gives the functionality of file I/O by providing wrappers around the standard POSIX functions. All file system operations can have synchronous and asynchronous forms depending upon user requirements.
fs.writeFileSync
and fs.writeFile
overwrite the file by default, there is no need for extra checks if this is what you want to do. This is mentioned in the docs:
fs.writeFile
Asynchronously writes data to a file, replacing the file if it already exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With