• Jobs
  • About Us
  • Jobs
    • Home
    • Jobs
    • Courses and challenges
  • Businesses
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

517
Views
Node Js : How to read and update json file

Hello I am a new coder but I am having troubles trying to add a new user (req) to a json file of users I have for a fake bank. I'm more confused on the type of object these are and how to access them from data. I would appreciate any words of advice. Currently I can only add the new account in, but it replaces the other users in the file. So now I'm trying to add the old users and the new users before I import but I am unsure how. My main area on confusion is how to access and manipulate the "data" from fs.readfile

app.post('/Account', (req, res,) => 
 {
    var queryParameter = req.query;
    console.log(queryParameter.pin);
    console.log(queryParameter.firstName);
    console.log(queryParameter.lastName);
    console.log(queryParameter.Balance);
    console.log(queryParameter.email);
    const tempAccount = 
    { 
        pin: Number(queryParameter.pin),
        firstName: queryParameter.firstName.toString(), 
        lastName: queryParameter.lastName.toString(),
        Balance: Number(queryParameter.Balance),
        email: queryParameter.email.toString() 
    };

    let content = []; 
    var data2 = tempAccount;//JSON.stringify(tempAccount, null, 2);*/
    const fileName = "Routes/Users.json";
    let content2 = [];
    
    fs.readFile(fileName, 'utf8', function(err, data)
    {
      data = JSON.parse(data);
      content2.push(JSON.stringify(data));
    });
        
    content.push(content2);
    content.push(data2);

    fs.writeFile(fileName, content, (err) => 
    {
      if (err) throw err;
    console.log('Data written to file');
    })
    res.send(data);
    
});

Here is the json file: 
{
    "user": [
     {
      "pin": "1234",
      "firstName": "Peter",
      "lastName": "Parker",
      "balance": "50",
      "email": "spider@avenger.com"
     },
     {
      "pin": "5678",
      "firstName": "Steve",
      "lastName": "Rogers",
      "balance": "50",
      "email": "captain@avenger.com"
     },
     {
      "pin": "4321",
      "firstName": "Tony",
      "lastName": "Stark",
      "balance": "1000",
      "email": "iron@avenger.com"
     }
    ]
   }
over 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is the key problem:

let content2 = [];

fs.readFile(fileName, 'utf8', function(err, data)
{
  data = JSON.parse(data);
  content2.push(JSON.stringify(data));
});
    
content.push(content2);
content.push(data2);

JSON is useful as an interchangeable data format, but is not something you want to try to manipulate in your application. As soon as you use JSON.stringify(), your data becomes a string. The only way to manipulate it as regular data again is to use JSON.parse().

So, in your code, you're parsing data, but turning right around and stringifying it as JSON again, and then trying to push it to content2. Assuming there weren't any asynchronous issues (there are, but more on that later), content2 would just be an array containing a single string.

Two things need to change. First, you need to wait for the data from the file to be loaded before you do anything else. As @jarmod mentions in the comments, you can do this by using a synchronous form of readFile, but it's better to do this async so as not to freeze up your application while we wait for the file.

Untested code, but try something like this:

import * as fs from 'fs/promises';

const dataFile = 'data.json';

function async loadData() {
  return JSON.parse(
    await fs.readFile(dataFile)
  );
}

function async saveData(data) {
  await fs.writeFile(
    dataFile,
    JSON.stringify(data)
  );
}

Now, when you want to use these functions, it's a bit easier:

app.post('/Account', async (req, res, next) => {
  const data = await loadData();
  
  // ... do other things here ...
  // For example:
  // data.user.push({ firstName: 'Brad' });
  
  await saveData(data);
});

Note that I changed this Express callback/handler to be async.

In the future, if you really want to use a local file-based database, check out SQLite3. It's very fast and extremely reliable.

over 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Show me some job opportunities
There's an error!