Node专栏-遍历目录结构组件walk模块

1,549 阅读1分钟

walk模块

npm地址:npm walk地址

node npm 遍历目录结构组件 walk

在node开发过程中,我们可能需要遍历某个目录这时我们可以自己写一个递归也可以直接使用这个模块。

使用教程

npm install --save walk


// 使用
var walk = require('walk');
var fs = require('fs');
var walker;

walker = walk.walk("/tmp", options);
 
walker.on("file", function (root, fileStats, next) {
    fs.readFile(fileStats.name, function () {
      // doStuff
      next();
    });
});
 
walker.on("errors", function (root, nodeStatsArray, next) {
    next();
});

walker.on("end", function () {
    console.log("all done");
});

事件

所有单独的事件回调函数的形式:function(root,stat,next){};

所有多个时间毁掉函数的形式是:function(root,stats,next){} 除了name是一个字符串数组。

所有错误事件毁掉函数形式是:function(root,stats,next){} . stat.error错误信息

root:

  • name 名称
  • directory 根目录
  • directories 文件目录
  • file
  • files
  • end
  • nodeError (stat failed)
  • directoryError ( stat succedded,but readdir failed)
  • errors (a collection of any errors encountered) 遇到任何错误的合集

使用案例

(function () {
  "use strict";
 
  var walk = require('walk');
  var fs = require('fs');
  var options;
  var walker;
 
  options = {
    followLinks: false
    // directories with these keys will be skipped(带有这些键的目录将被跳过,过滤设置不进行遍历的目录文件夹)
  , filters: ["Temp", "_Temp"]
  };
 
 
  walker = walk.walk("/tmp", options);
 
  // OR 或者使用异步遍历文件目录
  // walker = walk.walkSync("/tmp", options);
 
 
 //遍历寻找所有名称
  walker.on("names", function (root, nodeNamesArray) {
    nodeNamesArray.sort(function (a, b) {
      if (a > b) return 1;
      if (a < b) return -1;
      return 0;
    });
  });
  
  
 //遍历所有文件目录
  walker.on("directories", function (root, dirStatsArray, next) {
    // dirStatsArray is an array of `stat` objects with the additional attributes
    // * type
    // * error
    // * name
 
    next();
  });
 
 
 //遍历寻找文件,并读取
  walker.on("file", function (root, fileStats, next) {
    fs.readFile(fileStats.name, function () {
      // doStuff
      next();
    });
  });
  
  //错误情况捕获
  walker.on("errors", function (root, nodeStatsArray, next) {
    next();
  });
 
 //遍历结束
  walker.on("end", function () {
    console.log("all done");
  });
}());

案例-查找文件方法

使用walk遍历目录查找相应文件,封装一个查询文件的方法代码如下:

// search-file.js

const fs = require("fs");
const path = require("path");
const walk = require("walk");
const ora = require("ora");// 终端轮转组件

/**
 * @param {遍历的根目录} start 
 * @param {查询的文件名} filename 
 * @param {回调函数} cb 
 */
module.exports = function(start, filename, cb) {
  const loadingSearch = ora("正在搜索" + filename);
  // 轮转开始
  loadingSearch.start();
  var walker;

  walker = walk.walk(start, {
    followLinks: false,
    filters: ["node_modules", "dist"] // 过滤 node_modules和dist目录
  });

  walker.on("file", function(root, fileStats, next) {
    fs.readFile(fileStats.name, function() {
      // doStuff
      if (path.join(root, fileStats.name).indexOf(path.join(filename)) > -1) {
        walker.emit("end", { root: root, name: fileStats.name });
      } else {
        next();
      }
    });
  });

  walker.on("errors", function(root, nodeStatsArray, next) {
    next();
  });

  walker.on("end", function(file) {
    loadingSearch.stop();
    if (file) {
      cb(null, { root: path.resolve(file.root), name: file.name });
    } else {
      cb(true);
    }
  });
};

使用上述查询文件方法:

// demo.js
const searchFile = require("./search-file");

searchFile('../','.csproj',(err,file)=>{
    if(err){
        console.log("\n .csproj配置文件 未找到");
    }else{
        console.log(".csproj配置文件已找到:",file)
        //...找到后执行相关操作
    }
})