Array is empty outside the function scope even though it is declared in the global scope

Asked

Viewed 53 times

1

I’m starting in Javascript and Nodejs and I’m not able to understand pq even I declare an array in the global scope, when I try to access it outside the functions where I made the map the array comes empty.

I read two files without any problem and I can see the content through the console, but only inside the function, outside the array is empty, I need to use their contents to create another file. The contents of arrays sigla and nome I can only access inside readFile:

var fs = require("fs");

let sigla = [];
let nome = [];

fs.readFile("Estados.json", "utf8", (err, data) => {
  let states = JSON.parse(data);
  sigla = states.map((state) => {
    const { ID, Sigla, Nome } = state;
    return {
      id: ID,
      sigla: Sigla,
      estadoNome: Nome,
    };
  });
  console.log(sigla);
});

fs.readFile("Cidades.json", "utf8", (err, data) => {
  let cities = JSON.parse(data);
  nome = cities.map((city) => {
    const { ID, Nome, Estado } = city;
    return {
      id: ID,
      cidadeNome: Nome,
      cidadeEstado: Estado,
    };
  });
  console.log(nome);
});

for (i = 0; i < sigla.length; i++) {
  //prettier-ignore
  fs.writeFile(sigla[i].sigla + ".json",JSON.stringify(cidadeNome),(err) => {}
  );
}

1 answer

0


Browser other questions tagged

You are not signed in. Login or sign up in order to post.