Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!