Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

611
Visualizações
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"
     }
    ]
   }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda