node读取文件、文件夹

const path = require("path");
const fs = require("fs");
// 实现一个读取指定文件、文件夹,返回包含属性、方法的对象,

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 getConent(isBuffer = false) {
    if (this.isFile) {
      return await fs.promises.readFile(this.fileName, {
        encoding: isBuffer ? null : "utf-8",
      });
    } else {
      return null;
    }
  }
  async getChildren() {
    if (this.isFile) {
      return [];
    } else {
      let children = await fs.promises.readdir(this.fileName);
      children = children.map((childrenName) => {
        const childFileName = path.resolve(this.fileName, childrenName);
        return File.getFile(childFileName);
      });
      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 = new Date(stat.birthtime);
    const updateTime = stat.mtime;
    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 test() {
  const fileName = path.resolve(__dirname, "./fsFile");
  const result = await readDir(fileName);
  console.log(result);
  console.log(await result[0].getConent());
}
test();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值