0

I want to read all the JSON files from the data folder. I use the library https://www.npmjs.com/package/node-dir. I got a function, but it does not work synchronously. Variable replacements renders undefined.

async function giveHtml() {
    let replacements = await dir.readFiles(__dirname + '/data', { match: /.json$/ }, (err, content, next) => {
        if (err) {
            throw err
        }
        next()
    })
    console.log(replacements)
    return replacements
}

What's my mistake?

MegaRoks
  • 898
  • 2
  • 13
  • 30

4 Answers4

4

You can only await a promise, and dir.readFiles does not return a promise.

You can either convert it to use a promise or use a module that already returns a promise.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Note the `node-dir` module already has a `Promise`-based function. No need to convert or change modules. https://www.npmjs.com/package/node-dir#promisefiles-dir-callback- – wlh May 21 '19 at 14:01
1

dir.readFiles does not seem to return a promise, it returns undefined so that's what you're getting in return. You can try creating your own promise like this.

function giveHtml() {
  return new Promise((resolve, reject) => {
    dir.readFiles(__dirname + '/data', { match: /.json$/ }, (err, content, next) => {
      if (err) {
        return reject(err)
      }
      // do stuff per file if you want
      next()
    }, (err, files) => {
      if (err) {
        return reject(err)
      }
      resolve(files)
    })
  })
}
red-X
  • 5,108
  • 1
  • 25
  • 38
0

I think that your mistake is about not waiting for the response; You are returning the var replacements before the answer is given.

I'd try to call

console.log(replacements) 

after your

next()
federico scamuzzi
  • 3,708
  • 1
  • 17
  • 24
filo
  • 36
  • 3
0

async/await is syntactic sugar for a JavaScript Promise. await is listening for a resolved promise. In the npm package you are using, the readFiles function works with a callback, not a promise.

Use the promiseFiles function call instead: https://www.npmjs.com/package/node-dir#promisefiles-dir-callback-

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
wlh
  • 3,426
  • 1
  • 16
  • 32