I'm a little new to asyncronous code so I hope you guys can help me with this. I would like to take the contents of multiple JSON files read and pushed to an array, and then output through console.log. Of course, the first step has to conclude first before I can output anything to console.log, hence why I am using asyncronous code and learning about it.Here is my script I run with Node:const fs = require('fs'); const path = require('path'); const promisify = require('util').promisify; const readdir = promisify(fs.readdir); const dir = path.join(__dirname, 'data'); async function baz() { let contents = []; await readdir(dir, (err, files) => { files.forEach(file => { fs.readFile(path.join(dir, file), {encoding: 'utf-8'}, (err, data) => { if (err) throw err; if (path.extname(file) === '.json') { contents.push(JSON.parse(data)); } }) }) }) console.log(contents); } baz(); There are numerous JSON files in the /data directory. If I carry out this operation without async/await, i.e. console.log inside the forEach block, then the files are definitely recognised. However, logging contents to console in this code outputs nothing. I'm wondering about what may be the issue, and any help would be much appreciated.To recap:I want to read contents of JSON files;I want to push the contents of those files to an array;And then, when either it is successful or produces an error, I want to output the array to the console.This is what async/await means, as far as I know right now. Do the first thing, ensure it resolves, then do the thing which follows on from it.
Submitted January 05, 2019 at 08:09PM by beefyjon
No comments:
Post a Comment