Write to a File in JavaScript with examples

Contents

To create a new file or replace an existing one: fs.writeFile

To write to a file in JS you all you need is a built-in Node.js package “fs”:

const fs = require("fs");

const path = "/path/to/file.txt";
const data = "Sample text data";

function callback(error) {
  // error parameter will only be passed if anything goes wrong
  if (error) throw error;
  else console.log("Success");
}

fs.writeFile(path, data, callback);

This simple approach lets you create a file and put a primitive variable into it.

To add to the content of an existing file: fs.appendFile

What if instead of rewriting the content of a file every time you need to add some info to the end of the file? To solve this problem you might wanna take a look at appendFile method:

const fs = require("fs");

const path = "/path/to/file.txt";
const data = "Some extra data";

function callback(error) {
  ...
}

fs.appendFile(path, data, callback);

As you can see, appendFile shares the interface with writeFile. The only difference – the file will not be fully overwritten.

If the file doesn’t exist yet, appendFile will create a new one.

How to put an object into a file in JavaScript

The above methods work excellent while we’re working with primitive variables, such as strings or numbers. But what if you would need to save a more complex entity to a file – an object or an array?

Don’t worry, there is a simple solution: JSON.stringify

const fs = require("fs");

const path = "/path/to/file.json";
const rawData = {
  name: "John Doe",
  address: "221B Baker Street"
};

function callback(error) {
  ...
}

const data = JSON.stringify(rawData);

fs.writeFile(path, data, callback);

To convert the json data back to an object, you can use another built-in method JSON.parse.


Important note for beginner JavaScript developers: any file operations are only available on the server side, so to write to a file using js, you would need a running Node.js server.

There is no such api in the browser.

Learn more about I/O operations in JavaScript: WSchools

Author headshot
linkedingithubtoptal

Nick Trayze

Software Engineer, Toptal insider

Nick is a freelancer with over 10 years of experience, having contributed to nearly a hundred different projects across various industries.