I have a folder filled with json files and I am trying to push them all into an array. However, the outer array is blank. Any help on why this is happening or explaining a better approach would be appreciated.
var fs = require('fs');
var dataFolder = './jsonData/';
var arr = [];
fs.readdir(dataFolder, (err, files) => {
files.forEach(file => {
fs.readFile(dataFolder + file, 'utf8', function (err, data) {
if (err) throw err;
arr.push(data);
console.log (arr); // correct output
})
})
})
console.log (arr); //output is []
Sorry for how ugly it looks, but here's some of the output from the inner array:
[ '{\n "title": "A New Kind of Science [Hardcover]",\n "author": "Stephen Wolfram",\n "price": "$20.73",\n "shippingWeight": "5.6 pounds",\n "isbn10": "1579550088"\n}' ]
[ '{\n "title": "A New Kind of Science [Hardcover]",\n "author": "Stephen Wolfram",\n "price": "$20.73",\n "shippingWeight": "5.6 pounds",\n "isbn10": "1579550088"\n}', '{\n "title": "I Wear the Black Hat: Grappling with Villains (Real and Imagined) [Hardcover]",\n "author": "Chuck Klosterman",\n "price": "$15.49",\n "shippingWeight": "2.2 pounds",\n "isbn10": "1439184496"\n}' ]