Home > database >  Method push dont work in nodejs after conversion
Method push dont work in nodejs after conversion

Time:09-26

I am trying to append data using push method into an Array .I got the array via a json file that I have read through fs.readFileSynch then convert that data into object using JSON.parse() method .Below is my code for more explanation :

let data = fs.readFileSync("my_jsonfile_here"),(err)=>{
    if(err) return console.log(err);
});
data = JSON.parse( data.toString() ); // convert it to object
let appendDATA = data.push({name:"zadi"}) ; //adding data
console.log(appendDATA) // return number  why ???????????? 
// I was expecting this [{name:"donald"},{name:"zadi"}] as a result 

My json file look like this :

[
  {"name":"donald"}
]

CodePudding user response:

Array.push modifies the array, and doesn't return what you want.

Just use:

data.push({name:"zadi"});
console.log(data)

CodePudding user response:

If you check Array.push document, this method return length of array after push record

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push#return_value


Tip: In my opinion better use callback or promise for read file

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

(async () => {
  try {
    const body = await fsAsync.readFile('my_jsonfile_here');

    const data = JSON.parse(body.toString());
    const length = data.push({ name: 'zadi' });

    console.log('length', length);
    console.log('data', data);
  } catch (error) {
    console.error(error);
  }
})();

// Or use callback
const fs = require('fs');

fs.readFile('my_jsonfile_here', (error, body) => {
  if (error) {
    console.error(error);
    return;
  }

  const data = JSON.parse(body.toString());
  const length = data.push({ name: 'zadi' });

  console.log('length', length);
  console.log('data', data);
});
  • Related