获取包含字符串的文件夹中的所有文件,将文件名推入数组,然后使用节点FS返回数组

发布于 2025-01-26 10:09:26 字数 997 浏览 4 评论 0 原文

如标题所描述的那样,我想从特定目录中读取所有文件,然后返回所有内容中具有特定字符串的所有文件的名称。

这是我的代码到目前为止的外观:

const dirname = path.resolve("./results/");

async function readFiles(dirname) {
  const allResults = []
  fs.readdir(dirname, function(err, filenames) {
    if (err) {
      console.log(err);
      return;
    }
    filenames.forEach(async function(filename) {
      fs.readFile(dirname + "/" + filename, 'utf-8', function(err, content) {
        if (err) {
          console.log(err);
          return;
        }
        if (content.includes('content string')) {
          allResults.push(filename);
        }
      });
    });
  });
  return allResults;
}
readFiles(dirname).then((res) => {
  console.log(res);
})

我得到的结果是 []

因此我了解这是承诺和异步功能的问题,但是,这还不是我完全掌握的概念,尽管尝试了多种可能性组合( new Promise(),或。没有成功。

我缺少什么,以便它返回 allResults 仅在读取所有文件后数组?

As the title describes, I would like to read all files from a specific directory and return the names of all the files that have a specific string in its contents.

Here is how my code looks so far:

const dirname = path.resolve("./results/");

async function readFiles(dirname) {
  const allResults = []
  fs.readdir(dirname, function(err, filenames) {
    if (err) {
      console.log(err);
      return;
    }
    filenames.forEach(async function(filename) {
      fs.readFile(dirname + "/" + filename, 'utf-8', function(err, content) {
        if (err) {
          console.log(err);
          return;
        }
        if (content.includes('content string')) {
          allResults.push(filename);
        }
      });
    });
  });
  return allResults;
}
readFiles(dirname).then((res) => {
  console.log(res);
})

The result I'm getting is []

so I understand it's an issue with promises and async functions, however, this is not a concept I fully grasp yet, and despite trying several combinations of possibilities (new Promise(), or .then, await, or readdirSync and readFileSync) I had no success.

What am I missing so that it returns the allResults array only once all files have been read?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过潦 2025-02-02 10:09:26

您应该放弃回调语法并使用 fs.promises api。这看起来更干净

const fs = require("fs").promises;
const path = require("path");
const dirname = path.resolve("./results/");

async function readDir(dirname) {
  const allResults = [];

  try {
    const files = await fs.readdir(dirname);

    for (let i = 0; i < files.length; i++) {
      const fileName = files[i];

      try {
        const content = await fs.readFile(`${dirname}/${fileName}`, {
          encoding: "utf-8"
        });

        if (content.includes("content string")) {
          allResults.push(fileName);
        }
      } catch (error) {
        console.log(error.message);
      }
    }

    return allResults;
  } catch (error) {
    console.log(error);
  }
}

readDir(dirname).then(data => {
  console.log(data);
});

You should ditch callback syntax and use fs.promises Api. This looks much cleaner

const fs = require("fs").promises;
const path = require("path");
const dirname = path.resolve("./results/");

async function readDir(dirname) {
  const allResults = [];

  try {
    const files = await fs.readdir(dirname);

    for (let i = 0; i < files.length; i++) {
      const fileName = files[i];

      try {
        const content = await fs.readFile(`${dirname}/${fileName}`, {
          encoding: "utf-8"
        });

        if (content.includes("content string")) {
          allResults.push(fileName);
        }
      } catch (error) {
        console.log(error.message);
      }
    }

    return allResults;
  } catch (error) {
    console.log(error);
  }
}

readDir(dirname).then(data => {
  console.log(data);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文