DEV Community

miku86
miku86

Posted on • Edited on

NodeJS: How To Read A JSON File From Your Machine

Intro

So we installed NodeJS on our machine.

Now we want to learn how to read a JSON file from our machine using the File System (FS) module.

Create a file with some data

  • Open your terminal
  • Create a file named data-read.json:
touch data-read.json
Enter fullscreen mode Exit fullscreen mode
  • Add some JSON data into it:
[{ "id": 1, "name": "miku86" }]
Enter fullscreen mode Exit fullscreen mode

Write a simple script

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

const FILE_NAME = 'data-read.json';

const readFileAsync = () => {
  fs.readFile(FILE_NAME, (error, data) => {
    console.log('Async Read: starting...');
    if (error) {
      console.log('Async Read: NOT successful!');
      console.log(error);
    } else {
      try {
        const dataJson = JSON.parse(data);
        console.log('Async Read: successful!');
        console.log(dataJson);
      } catch (error) {
        console.log(error);
      }
    }
  });
};

readFileAsync();
Enter fullscreen mode Exit fullscreen mode

Note: We are using the async readFile function to read data, because we don't want to block other tasks. You can also read data synchronous using readFileSync, 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-read.json';

const readFileAsync = () => {
  // run async function to read file
  fs.readFile(FILE_NAME, (error, data) => {
    console.log('Async Read: starting...');

    if (error) {
      // if there is an error, print it
      console.log('Async Read: NOT successful!');
      console.log(error);
    } else {
      try {
        // try to parse the JSON data
        const dataJson = JSON.parse(data);
        console.log('Async Read: successful!');
        console.log(dataJson);
      } catch (error) {
        // else print an error (e.g. JSON was invalid)
        console.log(error);
      }
    }
  });
};

// run the function
readFileAsync();

Enter fullscreen mode Exit fullscreen mode

Run it from the terminal

  • Run it:
node index.js
Enter fullscreen mode Exit fullscreen mode
  • Result:
Async Read: starting...
Async Read: successful!
[ { id: 1, name: 'miku86' } ]
Enter fullscreen mode Exit fullscreen mode

Further Reading


Questions

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

Top comments (1)

Collapse
 
masekere profile image
Gift Masekere • Edited

We can load a json file synchronously using the require CommonJs feature.

const data = require('data-read.json')

// printing out the data
console.log(data)
Enter fullscreen mode Exit fullscreen mode

we can also make use of guard clauses to clean our asynchronous code

    fs.readFile('data.json', (error, data) => {
        if (error) {
            console.log('Async Read: NOT successful!');
            console.log(error);

            return
        }

        console.log('Async Read: starting...');

        try {
            const dataJson = JSON.parse(data);
            console.log('Async Read: successful!');
            console.log(dataJson);
        } catch (error) {
            console.log(error);
        }
    });
Enter fullscreen mode Exit fullscreen mode