Home > Blockchain >  Write objects into Array file inside for loop - NodeJS
Write objects into Array file inside for loop - NodeJS

Time:11-06

I'm running a POST request inside for loop function and the response should be stored as an object in an array file.

This is the code that I'm running:

var arrayFile = fs.createWriteStream("arrayFile.json", {
    flags: "a"
})

for (var x = 0; x < 2; x  ) {

    await axios
        .post(destinationURL, config)
        .then(res => {

            const obj = {
                id: x,
                user: config.user,
                password: config.password,
            }

            arrayFile.write(JSON.stringify(obj, null, 2), "utf-8")

        })
}

Here is the result inside arrayFile.json:

{
  "id": 0,
  "user": "testUser1",
  "password": "ThisIsPassword"
}{
  "id": 1,
  "user": "testUser2",
  "password": "ThisIsPassword"
}

Few things that I notice is comma after each object is missing and square brackets as well.

This is how it should look:

[
    {
    "id": 0,
    "user": "testUser1",
    "password": "ThisIsPassword"
  },
  {
    "id": 1,
    "user": "testUser2",
    "password": "ThisIsPassword"
  }
]

And of course the next time I run the function it should just keep writing the new objects into this array without removing the previous entries. I reckon I'm doing something wrong in the way the objects are being written onto the file, but I just cant figure it out.

Looked at solutions on Stackoverflow, however I have not yet found a solution for this exact problem where fs is being utilized inside a for loop function and then writing it onto an array file without overwriting previous objects.

CodePudding user response:

// var arrayFile = fs.createWriteStream("arrayFile.json", { flags: "a" })
var fs = require('fs');
var array = JSON.parse(fs.readFileSync("arrayFile.json", 'utf8'));
array = array ? array : [];

for (var x = 0; x < 2; x  ) {
  await axios
    .post(destinationURL, config)
    .then(res => {
      const obj = {
        id: x,
        user: config.user,
        password: config.password,
      }
      array.push(obj)
    })
}

let arrayJSON = JSON.stringify(array, null, 2)
fs.writeFile("arrayFile.json", arrayJSON, (err) => {
  if (err) {
    console.error(err);
  }
});

You are trying to read file as string and appending to it as a string

You could try

  • reading arrayFile.json as an array object

  • push the new data into array

  • write the new array into the file replacing the old one

  • Related