Node.js append to json file (2024) | TechGeekNext

Node.js append to json file (2024)

In this tutorial, we will learn how append or add the json data to json file in Node.js application using javascript.

Q: What is fs module in Nodejs?
Ans:

Node.js provides an inbuilt component called FS (File System). The Node. js file system module enables us to interact with our computer's file system.

Import NPM modules

  1. Create new folder for the project and open it in Visual Studio Editor.
  2. You can install Visual Studio Editor.
  3. Node.js Visual Studio Editor
  4. Create new file student-app.js under the project or while executing below npm command will point to default file called index.js
  5. The npm init command will install or create the package.json file if you run it as follows.
    D:\nodejs\file-example>npm init
    This utility will walk you through creating a package.json file.
    It only covers the most common items, and tries to guess sensible defaults.
    
    See `npm help init` for definitive documentation on these fields
    and exactly what they do.
    
    Use `npm install <pkg>` afterwards to install a package and
    save it as a dependency in the package.json file.
    
    Press ^C at any time to quit.
    package name: (file-example)
    version: (1.0.0)
    description: Nodejs file example
    entry point: (student-app.js)
    test command:
    git repository:
    keywords:
    author: techgeeknext
    license: (ISC)
    About to write to D:\nodejs\file-example\package.json:
    
    {
      "name": "file-example",
      "version": "1.0.0",
      "description": "Nodejs file example",
      "main": "student-app.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "techgeeknext",
      "license": "ISC"
    }
    
    
    Is this OK? (yes) yes
  6. package.json
    {
        "name": "file-example",
        "version": "1.0.0",
        "description": "Nodejs File Sysytem example",
        "main": "student-app.js",
        "scripts": {
            "test": "echo \"Error: no test specified\" && exit 1"
        },
        "author": "techgeeknext",
        "license": "ISC"
    }

Node.js Append to Json File

To append json data/elements to a json file, read the file, parse the JSON, push the new result to the array, convert into a string, and save it.

const fs = require('fs')


//check if file exist
if (!fs.existsSync('student.json')) {
    //create new file if not exist
    fs.closeSync(fs.openSync('student.json', 'w'));
}

// read file
const file = fs.readFileSync('student.json')
const data = {
    studentName: 'Joe',
    address: 'abc'
}

//check if file is empty
if (file.length == 0) {
    //add data to json file
    fs.writeFileSync("student.json", JSON.stringify([data]))
} else {
    //append data to jso file
    const json = JSON.parse(file.toString())
    //add json element to json object
    json.push(data);
    fs.writeFileSync("student.json", JSON.stringify(data))
}

Run the Node.js to append the data

  1. Node.js Write/Append to json File Javascript:
    Run the below command in Terminal to add students to json file.
    node student-app.js
  2. Json File
    We can see data is added/appended to student.json file.
    [{"studentName":"Joe","address":"abc"}]

Recommendation for Top Popular Post :