首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Node.js遍历目录

使用Node.js遍历目录
EN

Stack Overflow用户
提问于 2011-08-12 22:33:41
回答 4查看 35.6K关注 0票数 19

我对node.js中的这段代码有一个问题。我想递归地遍历目录树,并将回调action应用于树中的每个文件。这是我目前的代码:

代码语言:javascript
复制
var fs = require("fs");

// General function
var dive = function (dir, action) {
  // Assert that it's a function
  if (typeof action !== "function")
    action = function (error, file) { };

  // Read the directory
  fs.readdir(dir, function (err, list) {
    // Return the error if something went wrong
    if (err)
      return action(err);

    // For every file in the list
    list.forEach(function (file) {
      // Full path of that file
      path = dir + "/" + file;
      // Get the file's stats
      fs.stat(path, function (err, stat) {
        console.log(stat);
        // If the file is a directory
        if (stat && stat.isDirectory())
          // Dive into the directory
          dive(path, action);
        else
          // Call the action
          action(null, path);
      });
    });
  });
};

问题是,在for each循环中,通过变量path为每个文件调用stat。当回调被调用时,path已经有了另一个值,因此它将dive%s放到错误的目录中,或者为错误的文件调用action

也许这个问题可以通过使用fs.statSync很容易地解决,但这不是我喜欢的解决方案,因为它阻塞了进程。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-08-12 22:58:31

var path = dir + "/" + file;

您忘记了将path设置为局部变量。现在它不会在你背后的循环中被改变。

票数 16
EN

Stack Overflow用户

发布于 2014-05-14 22:43:13

为此,请使用node-dir。因为您需要对目录和文件执行单独的操作,所以我将使用node-dir提供两个简单的迭代器。

异步迭代目录及其子目录的文件,并将文件路径数组传递给回调。

代码语言:javascript
复制
var dir = require('node-dir');

dir.files(__dirname, function(err, files) {
  if (err) throw err;
  console.log(files);
  //we have an array of files now, so now we'll iterate that array
  files.forEach(function(filepath) {
    actionOnFile(null, filepath);
  })
});

异步迭代目录的子目录及其子目录,并将目录路径数组传递给回调。

代码语言:javascript
复制
var dir = require('node-dir');

dir.subdirs(__dirname, function(err, subdirs) {
  if (err) throw err;
  console.log(subdirs);
  //we have an array of subdirs now, so now we'll iterate that array
  subdirs.forEach(function(filepath) {
    actionOnDir(null, filepath);
  })
});
票数 12
EN

Stack Overflow用户

发布于 2020-02-07 05:16:45

这里有一个NPM模块:

npm dree

示例:

代码语言:javascript
复制
const dree = require('dree');
const options = {
    depth: 5,                        // To stop after 5 directory levels
    exclude: /dir_to_exclude/,       // To exclude some pahts with a regexp
    extensions: [ 'txt', 'jpg' ]     // To include only some extensions
};

const fileCallback = function (file) {
    action(file.path);
};

let tree;

// Doing it synchronously
tree = dree.scan('./dir', options, fileCallback);

// Doing it asynchronously (returns promise)
tree = await dree.scanAsync('./dir', options, fileCallback);

// Here tree contains an object representing the whole directory tree (filtered with options)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7041638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档