Home Linux HTML/CSS PHP PostgreSQL Node JS React VR Blog

NodeJS File System

Below you will find asynchronous code in action! As a NodeJS developer it is important to learn the Node File System.

    'use strict'; // prevents many common coding mistakes
    var fs = require('fs'); // file system

    // String: name/location of the file
    var file = 'cherry.json';
    // Object: data to place in file
    var data = {name: 'Candy',
                 title: 'Commander'}

    // Asynchronous Function: Make a File
    fs.writeFile(file, JSON.stringify(data), function (err) {
      if (err) {
        throw err;
      else {
        console.log(file + ' Saved!')

    // Asynchronous Function: Read a File
    fs.readFile(file,function (err, data) {
      if (err) throw err;
      else {
        var object = JSON.parse(data);

require filesystem - You need this line to use the fs.file functions.
file - The varible file holds the ➼ location where we want the file saved. In this case the file is called ➼ cherry.json and saved in the same directory.
data - This variable is an object. It holds ➼ data that we want to put into cherry.json.
fs.writeFile - Function to make the file ➼ cherry.json. If there is an err, it will log it. Otherwise it will save the file and log ➼"cherry.json saved."
fs.readFile - This is a function that reads a json file, ➼ parses it into an object and ➼ logs it. In this example it would log ➼"{ name: 'Candy', title: 'Commander'}"

Previous Lesson | Next Lesson