Skip to content
Related Articles

Related Articles

How to work with Node.js and JSON file ?
  • Difficulty Level : Easy
  • Last Updated : 14 Jul, 2020

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.

JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging data.

Creating a Script: Node.js scripts are created with the js file extension. Below is an example script stored as app.js file. It is a common convention to write your main executable file as app.js.




console.log('Hello Node.js!');

Running a Script: We can run a Node.js script using the node app.js command. Open a terminal window and navigate to the directory where the script exists.

Output:



Hello Node.js

Importing Node.js Core Modules: Node.js contains some built-in modules. These modules are comes with Node, so no installation is required for them. One of the most used module is file system or fs module. The fs module provides an API for interacting with the file system or basically it provides functions that we can use to manipulate the file system. For importing any module, we make use of the require() function. The script uses writeFileSync to write a message to demo.txt. After running the script, we will find the demo.txt file with the data written the same as the given parameter in writeFileSync function. If the ‘demo.txt’ file doesn’t exist in the directory a new file with the same name is created.




const fs = require('fs')
  
//  Writing to a file
fs.writeFileSync('demo.txt', 'geeks'

Exporting from Files: The module.exports is an object which comes inbuilt with node package. To use any function in another file, we must export it from the file that has its definition and import it in the file where we wish to use it.




// File Name: index.js
const demo = () => {
  console.log('This Functions uses'
          + ' ES6 arrow operator');
}
  
// We can export multiple functions
// by exporting an object of functions
// instead of a simple function
  
module.exports = check

Importing our Own Files: The require function can also be used to load our own JavaScript files. We have to provide a relative path to the file that we want to load script.




// File Name : app.js
  
// This index variable can be used
// to access all the exported methods
// of index.js in this file.
const index = require('./index.js');
  
// Executes all the functions
// contained in index.js
index();
  
// For any specific function use:
// Imported_variable.function_name()
index.check();

Writing and reading JSON file: JavaScript provides two methods for working with JSON. The first is JSON.stringify and the second is JSON.parse. The JSON.stringify converts a JavaScript object into a JSON string, while JSON.parse converts a JSON string into a JavaScript object. Since JSON is nothing more than a string, it can be used to store data in a text file.

Below code works only if data.json file exists as writeFileSync doesn’t create a JSON file if it does not exists. It creates a file if it does not exists in the case of a text file only.




// Importing 'fs' module
const fs = require("fs");
  
const geeksData = { title: "Node"
        article: "geeksforgeeks" };
  
// Covert JavaScript object into JSON string
const geeksJSON = JSON.stringify(geeksData);
  
// Covert JSON string into object
const geeksObject = JSON.parse(geeksJSON);
console.log(geeksObject.article);
  
// Adding more properties to JSON object
geeksObject.stack = "js";
geeksObject.difficulty = 1;
  
// Coverting js object into JSON string
// and writting to data.json file
const dataJSON = JSON.stringify(geeksObject);
fs.writeFileSync("data.json", dataJSON);
console.log(geeksObject);

Command to run the code:

node app.js

Output:

geeksforgeeks { 
    title: 'Node', 
    article: 'geeksforgeeks', 
    stack: 'js', 
    difficulty: 1 
}
My Personal Notes arrow_drop_up
Recommended Articles
Page :