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

105
Visualizações
write into json file with fs.append

I am working on a project using node.js and am struggling to fit an JSON object at the right position into my already existing data. My file currently looks like this:

[
  {
    "id": "001",
    "name": "Paul,
    "city": "London"
  },
  {
    "id": "002",
    "name": "Peter,
    "city": "New York"
  },
...
]

I tried to arrange my data like:

var data = { id: id, name: name, city: city };

having the respective data stored in those variables. Then I used var json = JSON.stringify(data) and tried

fs.appendFile("myJSONFile.json", json, function (err) {
        if (err) throw err;
        console.log('Changed!');
    }); 

The file changes indeed but the new entry is positioned after the square bracket.

[
  {
    "id": "001",
    "name": "Paul,
    "city": "London"
  },
  {
    "id": "002",
    "name": "Peter,
    "city": "New York"
  },
...
]{"id":"004","name":"Mark","city":"Berlin"}

How do I get it alongside the previous entries? Any help would be truly appreciated!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to first read the file, in your case you are storing an array in the file. So, you need to push your object to the array that you read from the file, and write the result back to the file (not append):

const fs = require('fs/promises');

// ...

const addToFile = async data => {
  let fileContents = await fs.readFile('myJSONFile.json', { encoding: 'utf8' });
  fileContents = JSON.parse(fileContents);
  fileContents.push(data);
  await fs.writeFile('myJSONFile.json', JSON.stringify(fileContents, null, 2), { encoding: 'utf8' });
};
about 4 years ago · Juan Pablo Isaza Relatório

0

You need to read current file, parse JSON content, modify it and then save the modified content:

const jsonString = fs.readFileSync(path);
const jsonObject = JSON.parse(jsonString);
jsonObject.push(item);
fs.writeFileSync(path, JSON.stringify(jsonObject));
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