首页 > 解决方案 > 遍历文件夹中的文件(javascript)

问题描述

我正在寻找遍历文件夹中的文件。我不知道运行脚本时文件的名称是什么,我只想获取名称。

我希望它像这样运行,但我不知道如何。我明白为什么这不起作用,但我不明白如何让它按我想要的方式工作。

for (file in "./levels/") {
    console.log(file)
}

有没有办法让它像这样运行?

标签: javascriptnode.js

解决方案


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)

推荐阅读