How to Write to a file in JavaScript Posted in Polyglotbits on 23 of Aug, 2016

Writing a file in Javascript is as easy as using the built-in method fs.writeFile, and as such matches the read file method quite well

var fs = require('fs');
fs.writeFile("file.txt", "This is the new file content.", function(err) {
    if(err) {
        return console.log(err);
    console.log("The file was saved!");

We require the fs package, and use it’s writeFile function to write the contents to the file.js file.

This method is async - there is a sync version as well.

More about JavaScript