首页
学习
活动
专区
工具
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
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7041638

复制
相关文章

相似问题

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