Open In App

How to push data to array asynchronously & save it in Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will walk through the process of building a small Node.js application that allows users to push data to an array asynchronously and save it. This article is intended for beginners who are just starting out with Node.js and want to learn how to build a basic application.

An asynchronous function is a function that runs in the background and does not block the main execution thread. Here are some of the most often-used ways to handle asynchronous code in Node.js:

  1. Callbacks: This is the traditional method of handling asynchronous code in Node.js. A callback is a function that is passed as an argument to another function and is executed after the main function has finished executing. Callbacks are easy to understand and use, but can become messy and hard to maintain for complex applications.
  2. Promises: Promises are objects that represent the completion or failure of an asynchronous operation. They provide a way to handle asynchronous code in a more organized and readable manner. Promises have a then method, which is executed when the promise is resolved, and a catch method, which is executed when the promise is rejected.
  3. Async/Await: This is a more modern way of handling asynchronous code in Node.js. Async/Await uses async functions and the await operator to simplify the writing of asynchronous code. An async function returns a promise, and the await operator allows us to wait for a promise to be resolved before moving on to the next line of code.

Let’s explore the power of all three of them!

 

Steps to create a project:

Step 1: Create a new project directory and navigate to it.

mkdir async-data-pusher
cd async-data-pusher

Step 2: Initialize the project with npm.

npm init -y

Step 3:  Install the required packages: express, body-parser, and fs.

npm install express body-parser fs

Step 4: Create two files called app.js and index.html.

Project Structure:

How to push data to array asynchronously & save in Node.js?

How to push data to array asynchronously & save in Node.js?

Example 1: This application will have a simple HTML interface for users to enter data, and the data will be saved to a file on the server using Node.js. The application will use the express library for handling HTTP requests and the body-parser library for parsing incoming data. We will also use the fs module in Node.js to handle file system-related operations.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Node App</title>
</head>
  
<body>
    <h1>Create new record</h1>
    <form action="http://localhost:3000/add" 
        id="addForm" method="post">
        <label for="fname">First Name</label>
        <input type="text" name="fname" required />
        <br><br>
        <label for="lname">Last Name</label>
        <input type="text" name="lname" required />
        <br><br>
        <button type="reset">Clear</button>
        <button type="submit">Add record</button>
    </form>
</body>
  
</html>


Javascript




const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
  
// Create a new instance of express framework
const app = express();
const port = 3000;
  
// Use the body-parser library to parse
// incoming JSON and URL-encoded data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
  
const data = [];
  
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html')
})
  
// Create a new endpoint for the POST method that
// accepts data to be added to the data array
app.post('/add', (req, res) => {
    const record = req.body;
    const obj = {
        fname: record.fname,
        lname: record.lname
    }
    data.push(obj);
  
    // Write the data array to a file called data.json
    fs.writeFile('./data.json', JSON.stringify(data), 
    (err) => {
        if (err) {
            console.error(err);
            return res.status(500)
                .send('Error saving data');
        }
        res.status(200)
            .send(`<h2>Data saved successfully :)</h2>`);
    });
});
  
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});


The asynchronous function in the above code is the fs.writeFile function, which is used to save the data to a file. This function takes three arguments: the file name, the data to be written, and a callback function that is called once the file has been written. The fs.writeFile function is asynchronous, meaning it will not block the main execution thread and will run in the background. Once the file has been written, the callback function is called and the result is sent back to the user.

Steps to run the application

Step 1: Start the node server or run the application with the below command:

node app.js

Step 2: Type the following address in the address bar on your browser,

http://localhost:3000

Output:

How to push data to array asynchronously & save in Node.js?

How to push data to array asynchronously & save in Node.js?

Explanation: After entering the data, hit enter or submit button. Once the data has been pushed to the array, we can save it in a file for later use. This can be done by using the fs module in Node.js. The fs module allows you to read and write files in Node.js. The above code will save the data in a file called data.json in the same directory as your Node.js file.

Output after Add Record action

 

Example 2: In this example, you will learn how to use async/await and promise functions in Node.js to push data to an array asynchronously and save it. These functions allow us to perform asynchronous operations and handle errors in a clean and organized manner. With the help of these functions, we can build applications that are faster, more efficient, and easier to maintain within the same project directory you can create a new JavaScript file:

index.js

Javascript




const fs = require('fs');
  
let dataArray = [];
  
const addData = (newData) => {
    return new Promise((resolve, reject) => {
        if (newData) {
            dataArray.push(newData);
            resolve();
        } else {
            reject(new Error('Invalid data'));
        }
    });
};
  
const saveData = async () => {
    try {
        await addData({ id: 1, name: 'John' });
        await addData({ id: 2, name: 'Jane' });
        await addData({ id: 3, name: 'Jim' });
        fs.writeFile('./dataArray.json'
        JSON.stringify(dataArray), (err) => {
            if (err) throw err;
        });
    } catch (err) {
        console.error(err);
    }
};
  
saveData();


Run or execute the code with the below command:

node index.js

The above code will save the data in a file called dataArray.json in the same directory as your Node.js file.

dataArray.json file: 

How to push data to array asynchronously & save in Node.js?

How to push data to array asynchronously & save in Node.js?

Explanation: First, we import the fs module, which is part of the Node.js standard library and provides file system-related operations. We then initialize a variable called dataArray as an empty array, which will store our data.

The addData function takes a new data object as an argument and returns a promise. The function checks if the newData argument is defined. If it is defined, it pushes the new data to the dataArray and resolves the promise. If newData is not defined, the promise is rejected with an error message.

The saveData function is declared with the async keyword. The saveData function uses the await operator to wait for the promise returned by addData to be resolved before adding the next data. After all the data has been added, the function uses the fs.writeFile function to save the dataArray to a file as a JSON string. If any errors occur during the save, the catch block will be executed to handle the error.

In this example, the use of async and Promise functions makes the code more readable and easier to maintain. It also provides a way to handle errors in an organized and readable manner.

With this foundation, you can expand and build upon the concepts covered in this article to create more complex and dynamic applications.



Last Updated : 21 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads