【问题标题】:Path system in WindowsWindows 中的路径系统
【发布时间】:2020-11-05 04:37:07
【问题描述】:

我想为我的节点项目 package.json 脚本提供一个路径。我有一个名为 X 的文件夹。X 有 10 个文件夹,其中一个有文件 Y。我不知道哪个文件夹有文件 Y。我如何写路径?

【问题讨论】:

  • 如果您不理解问题或需要更多信息,请在下方评论。请不要向下放弃。谢谢
  • 我没有投反对票,但是我也不清楚这个问题。您是否尝试在X 的子文件夹之一中查找文件Y,然后返回/打印路径?

标签: node.js windows path node-modules


【解决方案1】:

如果您尝试在X 的子文件夹之一中查找文件Y,然后返回/打印路径,您可以尝试以下操作。这将查看传递的目录中的所有文件,如果有子目录,则递归地继续这样做:

const path = require('path');
const fs = require('fs');

async function findFileRecursively(fileName, currentDirectory) {
    const files = await fs.promises.readdir(currentDirectory);
    for (let currFile of files) {
        const filePath = path.join(currentDirectory, currFile);
        const stats = await fs.promises.stat(filePath);
        if (currFile === fileName) {
            return filePath;
        } else if (stats.isDirectory()) {
            const result = await findFileRecursively(fileName, filePath);
            if (result) {
                return result;
            }
        }
    }

}

(async () => {
    try {
        const result = await findFileRecursively("filename.txt", './path-to-basefolder');
        if (result) console.log("File found at path: " + result)
        else console.log("File could not be found");
    } catch (err) {
        console.log(err.message);
    }
})();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    相关资源
    最近更新 更多