Node.js Read Write File Example (2024) | TechGeekNext

Node.js Read Write File Example (2024)

In this tutorial, we will learn how to perform operations on json files such as creating, reading, deleting, and so on in Node.js application.

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 System example",
        "main": "student-app.js",
        "scripts": {
            "test": "echo \"Error: no test specified\" && exit 1"
        },
        "author": "techgeeknext",
        "license": "ISC",
        "dependencies": {
            "yargs": "^17.5.1"
        }
    }

Project Structure

Node.js Read Write File Example

Node.js Read File

We can use fs.readFileSync to read the file synchronously with the provided file path. We can also use fs.readFile fs file operation for reading file without synchronously.

const fs = require('fs')
const file = fs.readFileSync('student.json')

Node.js Write to File

We can use fs.writeFileSync to write the data to file synchronously. We can also use fs.writeFile fs file operation for writing data to file without synchronously.

const fs = require('fs')

const filePath = 'student.json'

const data = {
    studentName: 'Joe',
    address: 'abc'
 }

fs.writeFileSync(filePath, JSON.stringify(data))

Node.js File Operations using fs

  1. Create the student-service-impl.js file for implementation of all file handling operations (read,write,delete, etc).
  2. Import the fs dependency to perform file operations on provided file.
  3. The JSON.stringify() method converts a JavaScript object or value to a JSON string.
  4. The JSON.push() method will push the new result/data to the array.
  5. We will read and write to json data file.
const fs = require('fs')

const filePath = 'student.json'
/**
 * Method to check if files exist
 * If file not exist create the file
 * @param {*} filepath
 */
const checkFileExist = (filepath) => {
    if (!fs.existsSync(filepath)) {
        fs.closeSync(fs.openSync(filepath, 'w'));
    }
}

/**
 * Method to write josn element to json file
 * @param {*} studentName
 * @param {*} address
 */
const writeStudentData = (studentName, address) => {

    checkFileExist(filePath);

    const file = fs.readFileSync(filePath)
    const data = {
        studentName: studentName,
        address: address
    }

    if (file.length == 0) {
        writeToJsonFile(JSON.stringify([data]), studentName)
    } else {
        const json = JSON.parse(file.toString())
        //add json element to json object
        json.push(data);
        writeToJsonFile(JSON.stringify(json), studentName)
    }
}

/**
 * Method to write the data to json file
 * @param {*} json
 * @param {*} studentName
 */
const writeToJsonFile = (json, studentName) => {

    fs.writeFile("student.json", json,

        function (err) {
            if (err) throw err;

            console.log('Student added : ' + studentName)
        });

}

/**
 * Method to delete the json element from json file
 * @param {*} studentName
 */
const deleteStudent = (studentName) => {

    const file = fs.readFileSync(filePath)
    if (file.length == 0) {
        console.log('No Data')
    } else {
        const stds = JSON.parse(file.toString())

        //check if that student exist in file
        const students = stds.filter((std) => std.studentName !== studentName)


        //if present in file
        if (stds.length > students.length) {
            fs.writeFileSync(filePath, JSON.stringify(students))
            console.log('Student removed : ' + studentName)
        } else {
            console.log('Student not found : ' + studentName)
        }
    }
}

/**
 * Method to read all data from json file
 */
const getAllData = () => {
    const file = fs.readFileSync(filePath)
    if (file.length == 0) {
        console.log('No Data')
    } else {
        const stds = JSON.parse(file.toString())

        stds.forEach((std) => {
            console.log('Student Name: ' + std.studentName + ' Address: ' + std.address)
        })
    }
}

/**
 * Read the data by using student name
 * @param {*} studentName
 */
const readStudent = (studentName) => {
    const file = fs.readFileSync(filePath)
    if (file.length == 0) {
        console.log('No Data')
    } else {
        const stds = JSON.parse(file.toString())

        const student = stdExist(stds, studentName)

        student
            ? console.log('Student Name: ' + student.studentName + ' Address: ' + student.address)
            : console.log('Student not found : ' + studentName)
    }

}

/**
 * Check if student is exist in the json data
 * @param {*} stds
 * @param {*} studentName
 * @returns
 */
const stdExist = (stds, studentName) => {
    return stds.find(std => std.studentName === studentName)
}


module.exports = {
    writeStudentData: writeStudentData,
    deleteStudent: deleteStudent,
    getAllData: getAllData,
    readStudent: readStudent
}

Yargs command to handle file operations

We will use the first parameter as an action for our application to perform file operations in student-app.js, we may do so with yargs.command as follows.

const yargs = require('yargs')
const student = require('./student-service-impl.js')


//write operation
yargs.command({
    command: 'add',
    describe: 'Add new student',
    handler(argv) {
        student.writeStudentData(argv.studentName, argv.address)
    }
})

//read operation
yargs.command({
    command: 'get',
    describe: 'Read student by name',
    handler(argv) {
        student.readStudent(argv.studentName)
    }
})



// read all data
yargs.command({
    command: 'getAll',
    describe: 'Read all data',
    handler(argv) {
        student.getAllData()
    }
})

//remove operation
yargs.command({
    command: 'delete',
    describe: 'Delete student by name',
    handler(argv) {
        student.deleteStudent(argv.studentName)
    }
})

yargs.parse()

Run the Node.js file handling Example

Run the following file handling commands in the terminal to view the output.

  1. Node.js Write/Append to json File Javascript:
    Add students by changing it's name and address to file.
    node student-app.js add --studentName="Joe" --address="abc"
    node student-app.js add --studentName="Ruby" --address="zzz"
  2. Json File
    Node.js File Example
  3. Node.js Read from json File:
    node student-app.js get --studentName="Ruby"
  4. Node.js Read all data from json File:
    node student-app.js getAll
  5. Node.js Remove JSON element Javascript:
    node student-app.js delete --studentName="Ruby"
Node.js File Example

Recommendation for Top Popular Post :