user1165273
user1165273

Reputation:

Prevent file corruption on exiting node in middle of fs.writeFile

I'm reading and writing some txt/json files in Node.js that have become >25mb in file size. If the process is interrupted half way through an fs.writeFile I get an empty file. So basically, I'm wondering if anyone knows of a quick way to prevent file writes from being corrupted if the process is exited. Is there a way to catch the exit and wait until the fs.writeFile callback is called?

Upvotes: 3

Views: 1518

Answers (1)

Troy Gizzi
Troy Gizzi

Reputation: 2519

A common approach is to first write to a different file (e.g., instead of overwriting permanent-file.txt directly, write to temporary-file.txt), and then in the callback from fs.writeFile, use fs.rename to replace the permanent file with the temporary one (e.g., fs.rename('temporary-file.txt', 'permanent-file.txt');).

Upvotes: 4

Related Questions