Reputation:
I am looking to loop over files in a folder. I will not know what the names of the files will be when running the script, I just want to get the names.
I want it to run like this, but I can't figure out how. I understand why this does not work, but I do not understand how to make it work the way I want.
for (file in "./levels/") {
console.log(file)
}
is there a way to make it run like this?
Upvotes: 5
Views: 11189
Reputation: 456
const fs = require("fs");
fs.readdirSync(".levels/").forEach(file => {
//Print file name
console.log(file)
/*
Run this to print the file contents
console.log(readFileSync(".levels/" + file, {encoding: "utf8"}))
*/
})
//but if your goal is just to print the file name you can do this
fs.readFileSync(".levels/").forEach(console.log)
Upvotes: 5
Reputation: 812
The only way to loop through directories and/or files is to use fs
or some third party program like glob
fs.readdirSync("path/to/folder").forEach(name => console.log(name))
This will print out the names of each file in the directory.
Upvotes: 1
Reputation:
Just figured this out. using the fs module in node.js I am able to iterate over the files. here is the code I am using:
fs.readdirSync("./levels/").forEach((file) => {
console.log(file)
})
Upvotes: 4