const fs = require('fs');
const path = require('path');
class File {
constructor(fileName, name, ext, isFile, size, createTime, updateTime) {
this.fileName = fileName;
this.name = name;
this.ext = ext;
this.isFile = isFile;
this.size = size;
this.createTime = createTime;
this.updateTime = updateTime;
}
async getContent(isBuffer = false) {
if(!this.isFile) return null;
if(isBuffer) {
return await fs.promises.readFile(this.fileName)
}
return await fs.promises.readFile(this.fileName, 'utf-8');
}
async getChildren() {
if(this.isFile) return [];
let children = await fs.promises.readdir(this.fileName);
children = children.map(name => {
const result = path.resolve(this.fileName, name);
return File.getFile(result);
});
return Promise.all(children);
}
static async getFile(fileName) {
const stat = await fs.promises.stat(fileName);
const name = path.basename(fileName);
const ext = path.extname(fileName);
const isFile = stat.isFile();
const size = stat.size;
const createTime = stat.birthtime.toLocaleString();
const updateTime = stat.mtime.toLocaleString();
return new File(fileName, name, ext, isFile, size, createTime, updateTime);
}
}
// 读取一个目录中的所有子目录和文件
async function readDir(fileName) {
const file = await File.getFile(fileName);
return await file.getChildren();
}
async function deepChildren(fileList) {
for(let i = 0; i < fileList.length; i++) {
fileList[i].children = await fileList[i].getChildren();
if(fileList[i].children.length !== 0) {
await deepChildren(fileList[i].children);
}
}
}
标签:node,const,await,fileName,return,封装,js,isFile,children
From: https://www.cnblogs.com/bingquan1/p/18184105