Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

104
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda