Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Update Data in JSON File using Node?
Next article icon

How to work with Node.js and JSON file ?

Last Updated : 09 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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  } 


Next Article
How to Update Data in JSON File using Node?
author
anuanu0_0
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • JSON
  • Node.js-Misc

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
    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 Content Using require() M
    4 min read
  • How to Download a File Using Node.js?
    Downloading files from the internet is a common task in many Node.js applications, whether it's fetching images, videos, documents, or any other type of file. In this article, we'll explore various methods for downloading files using Node.js, ranging from built-in modules to external libraries. Usin
    3 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 Copy a File in Node.js?
    Node.js, with its robust file system (fs) module, offers several methods to copy files. Whether you're building a command-line tool, a web server, or a desktop application, understanding how to copy files is essential. This article will explore various ways to copy a file in Node.js, catering to bot
    2 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 f
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences