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

Javascriptnode.js

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Found the solution. fs.writeFileSync gets a third arguments for options that can be an object. So if you get the "File already exist" you should do.

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

Solution 3 - Javascript

When you say "best way", i think at performance and scalability and i'd say use the https://stackoverflow.com/questions/35178903/overwrite-a-file-in-node-js">asynchronous method

fs.writeFileSync(path,string) as the name suggest is synchronous (blocking api) the thread is held for the whole lifecycle of the request, that means your nodejs thread will be blocked until the operation finishes and this behavior in a production environment with simultaneous connections from multiple clients could kill your app.

Do not think at the single line of code, less code doesn't mean better performance.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomas KatzView Question on Stackoverflow
Solution 1 - JavascriptmihaiView Answer on Stackoverflow
Solution 2 - JavascriptTomas KatzView Answer on Stackoverflow
Solution 3 - JavascriptKarimView Answer on Stackoverflow