node.js 封裝操作檔案類

HuangBingQuan發表於2024-05-10
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);
        }
    }
}

相關文章