nodejs遍历目录的方法

来源:互联网 发布:洗牙多久一次 知乎 编辑:程序博客网 时间:2024/05/29 14:38

1. 使用fs模块遍历

1.1 同步操作

var fs = require("fs")var path = require("path")var root = path.join(__dirname)readDirSync(root)function readDirSync(path){var pa = fs.readdirSync(path);pa.forEach(function(ele,index){var info = fs.statSync(path+"/"+ele)if(info.isDirectory()){console.log("dir: "+ele)readDirSync(path+"/"+ele);}else{console.log("file: "+ele)}})}

1.2. 异步操作

var fs = require("fs")var path = require("path")var root = path.join(__dirname)readDir(path.join(root))function readDir(path){fs.readdir(path,function(err,menu){if(!menu)return;menu.forEach(function(ele){fs.stat(path+"/"+ele,function(err,info){if(info.isDirectory()){console.log("dir: "+ele)readDir(path+"/"+ele);}else{console.log("file: "+ele)}})})})}


2. 使用walk模块遍历

var walk = require('walk')var root = path.join(__dirname)var files = [],dirs = [];getFileList(path.join(root))function getFileList(path){var walker  = walk.walk(path, { followLinks: false }); walker.on('file', function(roots, stat, next) {    files.push(roots + '/' + stat.name);    next();}); walker.on('directory', function(roots, stat, next) {    dirs.push(roots + '/' + stat.name);    next();});walker.on('end', function() {    console.log("files "+files);console.log("dirs "+dirs);});}


0 0
原创粉丝点击