← All Articles

How to Write to a file in JavaScript

Posted on

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.

polyglotbitsjavascriptwrite-to-a-file