Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to overwrite a file using fs in node.js

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?

like image 667
Tomas Katz Avatar asked May 10 '17 12:05

Tomas Katz


People also ask

Does fs rename overwrite?

nodejs's fs. rename() overwrites files because that is how the Unix rename() is defined and fs.

Which method of fs module is used to delete a file in node JS?

Use fs. unlink() method to delete an existing file.

Which method of fs module is used to write a file in node JS?

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.

What is the use of fs in node JS?

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.


1 Answers

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.

like image 144
mihai Avatar answered Sep 27 '22 02:09

mihai