0

I have a folder that contains 13 Json files. I need to get all of those file's data and number of those files and putting data's in a query and export variables out of function. I tried with fs but I got some problems like I cant get data's out and I dont really understood it.

The Main File's code:

var dosya = {
  bilgi: [],
  sayi: []
}

fs.readdir("./bilgiler/kisi-bilgiler/", async (err, files) => {
  await files.forEach(f => {
    dosya.bilgi = fs.readFile(`./bilgiler/kisi-bilgiler/${f}`, handleFile)
  });
  dosya.sayi = files.length

  console.log(dosya.sayi)
  console.log(dosya.bilgi)
});
  • forEach doesn't work like this with await. https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – digitalniweb Aug 14 '23 at 17:15

1 Answers1

0

fs.readFile is an async function, so you need to pass a callback. You don't need to await the forEach step i believe. Also, make sure you're pushing data to the dosya.bigli instead of just assigning. This might work:

fs.readdir("./bilgiler/kisi-bilgiler/", async (err, files) => {
  files.forEach(f => {
    dosya.bigli.push(fs.readFileSync(`./bilgiler/kisi-bilgiler/${f}`, {}))
  });
  dosya.sayi = files.length

  console.log(dosya.sayi)
  console.log(dosya.bilgi)
});

Can't really test, but something along these lines.

Marian Udrea
  • 111
  • 3