NodeJS: How To Write Data As JSON To Your Machine

Intro

So we installed NodeJS on our machine.

Last time, we learned how to read data from our machine.

Now we want to learn how to write data as JSON to our machine using the File System (FS) module.

Write a simple script

  • Open your terminal
  • Create a file named index.js:
touch index.js
  • Add this JavaScript code into it:
const fs = require("fs");

const FILE_NAME = "data-write.json";
const NEW_DATA = [{ id: 2, name: "Max" }];

const writeFileAsync = (newData) => {
  const stringifiedData = JSON.stringify(newData);

  fs.writeFile(FILE_NAME, stringifiedData, (error) => {
    if (error) {
      console.log("Async Write: NOT successful!");
      console.log(error);
    } else {
      console.log("Async Write: successful!");
      console.log(stringifiedData);
    }
  });
};

writeFileAsync(NEW_DATA);

Note: We are using the async writeFile function to write data, because we don't want to block other tasks. You can also write data synchronously using writeFileSync, but this could block some other tasks.

Note: You can do a lot of stuff with the File System module, therefore read the docs of the FS module.


Every line explained

// import the file system module
const fs = require("fs");

// save the file name of our data in a variable (increase readability)
const FILE_NAME = "data-write.json";

// save the new data in a variable (increase readability)
const NEW_DATA = [{ id: 2, name: "Max" }];

const writeFileAsync = (newData) => {
  // convert the  JavaScript values to a JSON string
  const stringifiedData = JSON.stringify(newData);

  // run async function to write file
  fs.writeFile(FILE_NAME, stringifiedData, (error) => {
    if (error) {
      // if there is an error, print it
      console.log("Async Write: NOT successful!");
      console.log(error);
    } else {
      console.log("Async Write: successful!");
      console.log(stringifiedData);
    }
  });
};

// run the function
writeFileAsync(NEW_DATA);

Note: We are using JSON.stringify() to convert the JavaScript values to a JSON string.


Run it from the terminal

  • Run it:
node index.js
  • Result:
Async Write: successful!
[{"id":2,"name":"Max"}]

Next Steps

  • Q: What happens, when data-write.json already exists?
  • Q: How can we tackle this issue?
  • Q: Do we need some additional error handling? (=> Docs)

Further Reading


Questions

  • Did you ever use the fs Promises API, that uses Promises instead of Callbacks?