Search code examples
javascriptnode.jsarraysasynchronousnode-sqlite3

Cannot read property 'push' of undefined when i initialized the array


I'm trying to read data from a database put it in a array and then send it in a JSON file, when i finish reading the data and start putting the array in a JSON file with push i get an error that says:

Cannot read property 'push' of undefined

I searched for this on the internet and people say that the array its not initialized but mine is, here is my code:

const sqlite3 = require('sqlite3').verbose();
const fs = require("fs");
dades = [];
// obre la base de dades SQLLite
let db = new sqlite3.Database('EstacioCasa.db', sqlite3.OPEN_READONLY, (err) => {
  if (err) {
    console.log('-Error in the database connection-');
    return console.error(err.message);
  }
  console.log('-Connected to database-');
});



db.serialize(() => {
  db.each(`SELECT cons_w
          FROM Consum`, (err, row) => {
    if (err) {
      console.error(err.message);
    }
    dades.push(row.cons_w);
    console.log(dades);
  });
});

setTimeout(function() {
    const dadaObj =  dades.reduce((map, dada) => { 
    map.dades.push( { consum: dada} );
    return map;
    }, { energia: []})

    fs.writeFileSync("./energia.json", JSON.stringify(dadaObj, null, 4));
}, 3000); 


db.close((err) => {
  if (err) {
    console.error(err.message);
  } 
  console.log('-Disconnected from database-');
});

And the console when i execute the script: Console log


Solution

  • The dades it is complaining about is most likely the one in the reduce method where you try map.dades.push( { consum: dada} ); The problem is that map has no key called dades.