Node.js & Express CRUD Example – Storing data in JSON file

In this post, we are going to see how to write a simple Node.js Express application to create a RESTful API. Also, we are not going to use a MongoDB here, instead, we will store the JSON data in a file and do the CRUD operations.

The idea behind not using the MongoDB is to get a clear picture of how the data storage works, so this example Node.js application will definitely help you to understand the basic concepts of CRUD operations.

Express is a popular web framework for Node.js., and it helps to create a web application easily.

So, let’s jump into the process instead of keep talking here.

Prerequisite:
Node.js should be installed on your system, if you don’t have please download and install it.

Step 1: Initialize a node project 

Create a folder somewhere in your system, give any name you like (eg., nodejsexpress), after creating the folder create a file called app.js and then open the command prompt and run the below command inside the newly created folder.

$ npm -y init

After running the above command, you should see a file created called, package.json with few lines of code something like this.

package.json

{
  "name": "nodejsexpress",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Don’t worry about this file right now, just make sure this file has been created. Next, we need to install the express framework.

Step 2: Install the required packages

We need the express package for our application so let’s install it by running the below command,

$ npm i express@4.17.1

The above command will install the express v4.17.1 package on your system.

Step 3: Let’s start writing CRUD operations

Open the app.js file and put the below lines of code to test if everything is up and running.

app.js

const express = require('express')
const app = express()

app.get('/', (req, res) => {
    const output = { value:  'hello world!' }
    res.send(output)
})

//configure the server port
app.listen(3000, () => {
    console.log('Server runs on port 3000')
})

Save the above file and go to the command prompt and run the below command to start the server.

 $ node app.js

Now, open any browser and type “http://localhost:3000” and you should see the JSON output as shown in the below screenshot.

helloworldoutput

If it works then we are good to go, before writing the CRUD operations, create another file users.json and write an empty square brackets [].

users.json

[]

Everything is ready now, let me put the entire app.js code here with the inline comments for you, so you can easily understand the logic.

CRUD – Create, Read, Update and Delete in Node.js

app.js

const express = require('express')
const fs = require('fs')

const app = express()

//this line is required to parse the request body
app.use(express.json())

/* Create - POST method */
app.post('/user/add', (req, res) => {
    //get the existing user data
    const existUsers = getUserData()
    
    //get the new user data from post request
    const userData = req.body

    //check if the userData fields are missing
    if (userData.fullname == null || userData.age == null || userData.username == null || userData.password == null) {
        return res.status(401).send({error: true, msg: 'User data missing'})
    }
    
    //check if the username exist already
    const findExist = existUsers.find( user => user.username === userData.username )
    if (findExist) {
        return res.status(409).send({error: true, msg: 'username already exist'})
    }

    //append the user data
    existUsers.push(userData)

    //save the new user data
    saveUserData(existUsers);
    res.send({success: true, msg: 'User data added successfully'})

})

/* Read - GET method */
app.get('/user/list', (req, res) => {
    const users = getUserData()
    res.send(users)
})

/* Update - Patch method */
app.patch('/user/update/:username', (req, res) => {
    //get the username from url
    const username = req.params.username

    //get the update data
    const userData = req.body

    //get the existing user data
    const existUsers = getUserData()

    //check if the username exist or not       
    const findExist = existUsers.find( user => user.username === username )
    if (!findExist) {
        return res.status(409).send({error: true, msg: 'username not exist'})
    }

    //filter the userdata
    const updateUser = existUsers.filter( user => user.username !== username )

    //push the updated data
    updateUser.push(userData)

    //finally save it
    saveUserData(updateUser)

    res.send({success: true, msg: 'User data updated successfully'})
})

/* Delete - Delete method */
app.delete('/user/delete/:username', (req, res) => {
    const username = req.params.username

    //get the existing userdata
    const existUsers = getUserData()

    //filter the userdata to remove it
    const filterUser = existUsers.filter( user => user.username !== username )

    if ( existUsers.length === filterUser.length ) {
        return res.status(409).send({error: true, msg: 'username does not exist'})
    }

    //save the filtered data
    saveUserData(filterUser)

    res.send({success: true, msg: 'User removed successfully'})
    
})


/* util functions */

//read the user data from json file
const saveUserData = (data) => {
    const stringifyData = JSON.stringify(data)
    fs.writeFileSync('users.json', stringifyData)
}

//get the user data from json file
const getUserData = () => {
    const jsonData = fs.readFileSync('users.json')
    return JSON.parse(jsonData)    
}

/* util functions ends */


//configure the server port
app.listen(3000, () => {
    console.log('Server runs on port 3000')
})

Please go through the inline comments to understand the CRUD logic, it is not so complicated if you are already good at plain JavaScript.

Save the above file and go to the command prompt and run the below command again, (NOTE: if the server is already running press CTRL + C to close it).

 $ node app.js

We have now POST, GET, PATCH, and DELETE created already in app.js, to test all these methods we need a REST client. If you already know what is Postman, you can test it easily. Anyways, I will show you how to do it with screenshots.

Step 4: Test our application

  • CREATE Method (http://localhost:3000/user/add)

Install the Postman chrome extension, open it and fill the “Request body” as shown in the screenshot below, make sure everything is selected as shown and click the “Send” button to see the output.

create-restapi-nodejs

If you see the “Response” as same as the above screenshot, everything is working fine already.

To confirm the data is stored in the users.json open it and check, the user data should now be written in the users.json file.

users.json 

[{"username":"agurchand","password":"testpass","fullname":"Agurchand Babu","age":33}]

The same way we can test the Read method now,

  • READ Method (http://localhost:3000/user/list)

Open Postman chrome extension, select the method as GET and put the URL as shown in the below screenshot.

read-restapi-nodejs

You should see the Response output as shown in the above screenshot.

  • Update Method (http://localhost:3000/user/update/:username) – :username is dynamic

Open Postman chrome extension, select the method as PATCH, and put the URL as shown in the below screenshot. Make sure to put the “Request Body” as well.

update-restapi-nodejs

Last but not least, let’s check the DELETE method as well,

  • DELETE Method (http://localhost:3000/user/delete/:username) – :username is dynamic

Go back to Postman chrome extension, select the method as DELETE, and put the URL as shown in the below screenshot. “Request Body” is not required for delete operation as per our code.

delete-restapi-nodejs

I hope this post helped you to understand the CRUD operation using Node.js, Express, and Node.js filesystem. Happy learning!

One thought on “Node.js & Express CRUD Example – Storing data in JSON file

Leave a Reply

Theme: Overlay by Kaira
Agurchand