UNPKG

@modern-js/runtime-utils

Version:

A Progressive React Framework for modern web development.

49 lines (48 loc) 1.74 kB
import "node:module"; import fs_extra from "@modern-js/utils/fs-extra"; import { createMemoryStorage } from "./storer/index.mjs"; class FileReader { async readFile(path, encoding = 'utf-8') { const { fs } = this; const _readfile = this._readFileFactory(fs); return _readfile(path, encoding); } async readFileFromSystem(path, encoding = 'utf-8') { const _readfile = this._readFileFactory(fs_extra); return _readfile(path, encoding); } _readFileFactory(fs) { return async (path, encoding = 'utf-8')=>{ const cache = await this.storage.get(path); if (null === cache) return null; if (cache) return this.encodingContent(cache, encoding); const isExistFile = await new Promise((resolve)=>{ fs.stat(path, (err, stats)=>{ if (err) return void resolve(false); stats.isFile() ? resolve(true) : resolve(false); }); }); if (isExistFile) { const content = await fs.promises.readFile(path); this.storage.set(path, content); return this.encodingContent(content, encoding); } this.storage.set(path, null); return null; }; } reset(fs) { fs && (this.fs = fs); return this.storage.clear?.(); } encodingContent(value, encoding) { if ('utf-8' === encoding) return value.toString(); return value; } constructor(storage){ this.fs = fs_extra; this.storage = storage; } } const fileReader = new FileReader(createMemoryStorage('__file__system')); export { FileReader, fileReader };