By Noxxxx from https://www.noxxxx.com/?post_type=post&p=1687
欢迎分享与聚合,尊重版权,可以联系授权
对于.
开头的隐藏文件也会被读取到。
'use strict';
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const readdirPromise = promisify(fs.readdir);
const statPromise = promisify(fs.stat);
class File {
constructor(filename, size) {
this.filename = filename;
this.size = size;
}
}
function scanFs() {
const dir = process.cwd();
const result = [];
function collect(dir) {
const basedir = dir;
return readdirPromise(dir).then(files =>
Promise.all(files.map(fn => {
const fullpath = path.join(dir, fn);
const realpath = path.relative(basedir, fullpath);
return statPromise(fullpath).then(stats => {
if (stats.isDirectory()) {
return collect(fullpath);
}
const file = new File(realpath, stats.size)
result.push(file)
})
}))
)
}
return collect(dir).then(() => result);
}
module.exports = scanFs;