Home > Software design >  DirectoryFiles is not iterable node js
DirectoryFiles is not iterable node js

Time:08-28

I am trying to make a program where it would map all of the json files in a specific directory. This question might not be good or be obvious because I am new to javascript. My code is:

const fs = require('fs');
const { glob } = require('glob')
const { promisify } = require('util');
const globPromise = promisify(glob);

// const dir = '/JSON';
// const files = fs.readdirSync(dir);
console.log(`Current directory: ${process.cwd()}`)

const directoryFiles = globPromise(`${process.cwd()}/JSON/*.json`);

console.log(`${process.cwd()}`)
const JSON = [];

for (const file of directoryFiles) {
    JSON.map(file);
}

console.log(JSON);

In that directory, I have 1 file called facts.json but plan to add more. I didn't really think this code would work from the start, but I want to know a way that I can actually make this work because right now I think the issue is that since the globPromise is a promise, it doesn't return the files in the way that is intended and cannot be iterated through a for loop.

Edit: I changed the line const directoryFiles = globPromise(${process.cwd()/JSON/*.json}) to fs.readdirSync(${process.cwd()}/JSON/) and now I get another error saying that facts.json is not a function probably because for some reason it thinks that it is a string not a file.

CodePudding user response:

globPromise() returns a promise. You promisified the plain callback version of glob to make globPromise() that returns a promise.

So, directoryFiles in your code is a promise. You have to use await or .then() on that promise to get the actual glob result. The promise, by itself, is not an iterable, thus the error you get.

globPromise(`${process.cwd()}/JSON/*.json`).then(directoryFiles => {
    for (const file of directoryFiles) {
        console.log(file);
    }
}).catch(err => {
    console.log(err);
})
  • Related