How to work with Node.js and JSON file ?
Last Updated :
09 Nov, 2022
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.
javascript
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.
javascript
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.
javascript
// 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.
javascript
// 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.
javascript
// Importing 'fs' module
const fs = require("fs");
const geeksData = { title: "Node",
article: "geeksforgeeks" };
// Convert JavaScript object into JSON string
const geeksJSON = JSON.stringify(geeksData);
// Convert 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;
// Converting js object into JSON string
// and writing 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
}
Similar Reads
How to read and write JSON file using Node ? Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises.JSON(JavaScript Object Notation) is a simple and t
3 min read
How to read and write files in Node JS ? NodeJS provides built-in modules for reading and writing files, allowing developers to interact with the file system asynchronously. These modules, namely fs (File System), offer various methods for performing file operations such as reading from files, writing to files, and manipulating file metada
2 min read
How to Add Data in JSON File using Node.js ? JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article.Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
4 min read
How to Update Data in JSON File using Node? To update data in JSON file using Node.js, we can use the require module to directly import the JSON file. Updating data in a JSON file involves reading the file and then making the necessary changes to the JSON object and writing the updated data back to the file. Table of ContentUsing require() Me
4 min read
How to Access the File System in Node.js ? In this article, we looked at how to access the file system in NodeJS and how to perform some useful operations on files. Prerequisite: Basic knowledge of ES6Basic knowledge of NodeJS NodeJS is one of the most popular server-side programming frameworks running on the JavaScript V8 engine, which uses
3 min read
How to open JSON file ? In this article, we will open the JSON file using JavaScript. Â JSON stands for JavaScript Object Notation. It is basically a format for structuring data. The JSON format is a text-based format to represent the data in form of a JavaScript object.Approach:Create a JSON file, add data in that JSON fil
2 min read
How to Open JSON File? JSON (JavaScript Object Notation) is a lightweight, text-based data format that stores and exchanges data. Let's see how we can create and open a JSON file.How to Create JSON Files?Before learning how to open a JSON file, it's important to know how to create one. Below are the basic steps to create
2 min read
How to load a JSON object from a file with ajax? Loading a JSON object from a file using AJAX involves leveraging XMLHttpRequest (XHR) or Fetch API to request data from a server-side file asynchronously. By specifying the file's URL and handling the response appropriately, developers can seamlessly integrate JSON data into their web applications.
3 min read
How to Use MongoDB and Mongoose with Node.js ? MongoDB is a popular NoSQL database that offers flexibility and scalability, making it an excellent choice for modern applications. Mongoose, a powerful ODM (Object Data Modeling) library, simplifies the interaction between MongoDB and Node.js by providing a schema-based solution for data validation
6 min read
How to add new functionalities to a module in Node.js ? Node.js is an open-source and cross-platform runtime environment built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isnât a framework, and itâs not a programming language. In this article, we will discuss how to add new functi
3 min read