用Node.js遍历一个目录 [英] Walking a directory with Node.js

查看:138
本文介绍了用Node.js遍历一个目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  var fs = require(fs); 
$ b $ //一般函数
var dive = function(dir,action){
//声明这是一个函数
if(typeof action!==function )
action = function(error,file){};
$ b $ //读取目录
fs.readdir(dir,function(err,list){
//返回出错信息
if(err )
return action(err);

//对于列表中的每个文件
list.forEach(function(file){
//完整路径文件
path = dir +/+ file;
//获取文件的统计信息
fs.stat(path,function(err,stat){
console.log stat);
//如果文件是目录
if(stat&& stat.isDirectory())
//跳入目录
dive(path,动作);
else
//调用动作
action(null,path);
});
});
});
};

问题在于每个循环的 文件通过变量路径。当调用回调函数时, path 已经有了另一个值,所以 dive 到错误的目录中,或者调用 action 为错误的文件。

也许这个问题很容易通过使用 fs来解决。 statSync ,但这不是我想要的解决方案,因为它阻止了这个进程。

解决方案

var path = dir +/+ file;



路径一个局部变量。现在它不会在循环后面改变。


I've got a problem with this code in node.js. I want to recursively walk through a directory tree and apply the callback action to every file in the tree. This is my code at the moment:

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);
      });
    });
  });
};

The problem is that in the for each loop stat is called for every file via the variable path. When the callback is called, path already has another value and so it dives into the wrong directories or calls the action for the wrong files.

Probably this problem could easily get solved by using fs.statSync, but this is not the solution I would prefer, since it is blocking the process.

解决方案

var path = dir + "/" + file;

You forgot to make path a local variable. Now it won't be changed behind your back in the loop.

这篇关于用Node.js遍历一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆