Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NodeJS递归遍历指定目录所有文件 #43

Open
varHarrie opened this issue May 11, 2022 · 0 comments
Open

NodeJS递归遍历指定目录所有文件 #43

varHarrie opened this issue May 11, 2022 · 0 comments
Labels
Milestone

Comments

@varHarrie
Copy link
Owner

varHarrie commented May 11, 2022

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

async function traverse(dir, callback) {
  const items = await fs.promises.readdir(dir, { withFileTypes: true });

  return Promise.all(
    items.map((item) => {
      const fullPath = path.join(dir, item.name);

      if (item.isDirectory()) {
        return traverse(fullPath, callback);
      }

      if (item.isFile()) {
        return callback(fullPath);
      }

      return Promise.resolve();
    }),
  );
}

await traverse(path.join(__dirname, '../src'), (filePath) => {
  console.log(filePath);
});
@varHarrie varHarrie added this to the Snippets milestone May 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant