fs.readdirSync包含子目录

时间:2018-10-25 07:19:39

标签: node.js fs

我正在尝试更改代码以将文件也包含在子目录中:

const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));

for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  client.commands.set(command.name, command);
}

我找到了一个对我来说似乎有点抽象的解决方案,当我尝试实现它时,我遇到了一个错误,这就是我尝试过的:

const { readdirSync, statSync } = require('fs');
const { join } = require('path');

const dirs = p => readdirSync(p).filter(f => statSync(join(p, f)).isDirectory())

const commandFiles = ('./commands');

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

我遇到以下错误:

Error: Cannot find module './commands/.'

我该怎么做才能使这项工作成功?

2 个答案:

答案 0 :(得分:0)

可以使用

const fs = require('fs');

const walk = function(dir) {
    let results = [];
    const list = fs.readdirSync(dir);
    list.forEach(function(file) {
        file = dir + '/' + file;
        file_type = file.split(".").pop();
        file_name = file.split(/(\\|\/)/g).pop();
        const stat = fs.statSync(file);
        if (stat && stat.isDirectory()) { 
            results = results.concat(walk(file));
        } else { 
            if (file_type == "js") results.push(file);
        }
    });
    return results;
}

const commandFiles = walk('./commands');

for (const file of commandFiles) {
    const command = require(`${file}`);

答案 1 :(得分:0)

只需使用 __dirname

const commandFiles = fs.readdirSync(__dirname+'/commands').filter(file => file.endsWith('.js'));