Write or Append to a File in Node.js with fs.writeFile and fs.writeFileSync

InstructorChris Achard

Share this video with your friends

Send Tweet

In node.js, you can require fs, and then call fs.writeFile with the filename, and data to write to that file (as a string or a buffer). That will overwrite the entire file, so to just append that data to the file instead, pass an options object with the flag key set to a. Or, you can use fs.appendFile. Make sure to handle errors using a callback as the last argument to writeFile and appendFile.

There are synchronous versions of each function as well, fs.writeFileSync and fs.appendFileSync, which will throw errors, instead of returning them in a callback.