给一个本地路径 nodejs 怎么读取这个路径下的所有文件 把这些文件罗列出来
发布于 10 年前 作者 babata01 88478 次浏览 最后一次编辑是 8 年前

给一个本地路径,nodejs 怎么读取这个路径下的所有文件 ,把这些文件罗列出来. 或者用html5 罗列出来。求指导

16 回复

fs 对象下的 API 就好了

诶没办法 ,自己写了一个递归。诶 这 用到了这几个api var fs1 = require(‘fs’); stats = fs1.lstatSync(filePath);//查看文件属性 fs1.readdir();罗列文件夹下面文件, 需要的可以参考下

var fs = require('fs'),
    stdin = process.stdin,
    stdout = process.stdout;
var stats = [];

fs.readdir(process.cwd(), function(err, files) {
    console.log(' ');

    if (!files.length) {
        return console.log(' \033[31m No files to show!\033[39m\n');
    }

    function file(i) {

        var filename = files[i];


        fs.stat(__dirname + '/' + filename, function(err, stat) {
            stats[i] = stat;
            if (stat.isDirectory()) {
                console.log(' ' + i + ' \033[36m' + filename + '/\033[39m');
            } else {
                console.log(' ' + i + ' \033[90m' + filename + '\033[39m');
            }

            i++;

            if (i == files.length) {
                read();
            } else {
                file(i);
            }
        });
    }

    function read() {
        console.log(' ');
        stdout.write(' \033[33mEnter your choice : \033[39m');
        stdin.resume();
        stdin.setEncoding('utf8');
        stdin.on('data', option);
    }

    function option(data) {
        var filename = files[Number(data)];
        if (!files[Number(data)]) {
            stdout.write(' \033[mEnter your choice : \033[39m');
        } else if (stats[Number(data)].isDirectory()) {
            fs.readdir(__dirname + '/' + filename, function(err, files) {
                console.log(' ');
                console.log(' (' + files.length + 'files)');
                files.forEach(function(file) {
                    console.log(' - ' + file);
                });
                console.log(' ');
            });
        } else {
            stdin.pause();
            fs.readFile(__dirname + '/' + filename, 'utf8', function(err, data) {
                console.log(' ');
                console.log('\033[90m' + data.replace(/(.*) /g, ' $1') + '\033[39m');
            });
        }
    }

    file(0);
});

《了不起的node.js》 上的代码

嗯哼 这书还不赖

var fs = require(“fs”);

var path = “d:\WinRAR”;

function explorer(path){ fs.readdir(path, function(err,files){ if(err){ console.log(“error:\n”+err); return; }
files.forEach(function(file){ fs.stat(path+"\"+file+’’,function(err,stat){ if(err){ console.log(err); return; }

                if(stat.isDirectory()){
                    console.log(path+"\\"+file+"\\");
                    explorer(path+"\\"+file);
                }else{
                    console.log(path+"\\"+file);
                }
            
        });
    });

});    

}

explorer(path);

我自己写的 贴进来格式有点变化,markdown还不太会用

5楼正解~!

var fs = require(‘fs’), util = require(‘util’), path = ‘D:/mp3’;

function explorer(path){

fs.readdir(path, function(err, files){
	//err 为错误 , files 文件名列表包含文件夹与文件
	if(err){
		console.log('error:\n' + err);
		return;
	}

	files.forEach(function(file){

		fs.stat(path + '/' + file, function(err, stat){
			if(err){console.log(err); return;}
			if(stat.isDirectory()){					
				// 如果是文件夹遍历
				explorer(path + '/' + file);
			}else{
				// 读出所有的文件
				console.log('文件名:' + path + '/' + file);
			}				
		});
		
	});

});

}

explorer(path);

ndir模块做了这件事

可以参考npm模块glob的实现,

glob可以使用与shell模式匹配一样的方式遍历文件目录树

var glob = require("glob")
// options is optional
glob("**", options, function (err, files) {
})

或者自己用递归的方式实现

const fs = require('fs')

let files = []
function ScanDir(path) {
  let that = this
  if (fs.statSync(path).isFile()) {
    return files.push(path)
  }
  try {
    fs.readdirSync(path).forEach(function (file) {
      ScanDir.call(that, path + '/' + file)
    })
  } catch (e) {
  }
}

ScanDir(process.cwd())
console.log(files)

Maybe the follow is what you want :)

/**
 * Read all files from build/ folder recursively
 */
function readDir(path){
    let sub = fs.readdirSync(path)

    // ignore hide files
    sub = sub.filter((e)=>{
        return e.indexOf('.') !== 0
    })

    // complete path
    sub = sub.map((e)=>{
        return _path.resolve(path, e)
    })

    if(sub.length === 0){
        console.log('😫  build文件夹下没有文件!'.error)
    }else{
        return sub
    }
}
function readPath(path){
    // Determine whether the path is dir or not
    let stat = fs.statSync(path)

    if(stat.isFile()){
        S3_files.push(path)
    }else if(stat.isDirectory()){
        let sub_children = readDir(path)

        sub_children.forEach((e)=>{
            readPath(e)
        })
    }
}
readPath(BUILD_PATH)
回到顶部