Reputation: 7105
I'm trying to use getStaticPaths
with extracted ids from JSON file names which are inside my public folder. My approach is as follows
export async function getStaticPaths() {
const directoryPath = path.join(__dirname, "../../../../public/db/");
var fileNames = [];
fs.readdir(directoryPath, function (err, files) {
if (err) {
return console.log("Unable to scan directory: " + err);
}
files.forEach(function (file) {
fileNames.push(file.substring( 0, file.indexOf(".")))
});
});
console.log("fileNames",fileNames);
return {
fallback: false,
paths: [
{
params: {
reportId: "temp1",
},
},
{
params: {
reportId: "temp2",
},
},
],
};
}
I'm trying to push the file names into an array called fileNames
. But I'm only seeing an empty array. I tried logging inside my forEach
method and there I can clearly see my names. So my question is why is the push method not doing anything here?
Upvotes: 3
Views: 6002
Reputation: 50288
That's because the readdir
callback is called asynchronously, and by the time you get to console.log("fileNames", fileNames)
the forEach
loop hasn't run yet.
I'd recommend using either the synchronous readdirSync
version.
const directoryPath = path.join(__dirname, "../../../../public/db/");
const fileNames = [];
const files = fs.readdirSync(directoryPath);
files.forEach(function (file) {
fileNames.push(file.substring(0, file.indexOf(".")));
});
console.log("fileNames", fileNames);
Or, the promise-based readdir
from fs/promises
.
import { readdir } from 'fs/promises';
const directoryPath = path.join(__dirname, "../../../../public/db/");
const fileNames = [];
try {
const files = await readdir(directoryPath);
files.forEach(function (file) {
fileNames.push(file.substring(0, file.indexOf(".")));
});
console.log("fileNames", fileNames);
} catch (err) {
console.log("Unable to scan directory: " + err);
}
Upvotes: 4