From 77154fa0696c23a898c071562ed0c037aa9fa5e4 Mon Sep 17 00:00:00 2001 From: yafu Date: Fri, 23 Feb 2024 17:27:58 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96utils=E5=BA=93fs=E5=B7=A5?= =?UTF-8?q?=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/run.js | 2 +- lib/types.js | 37 ++++++++-------- lib/utils/fs.js | 115 ++++++++++++++++++++++-------------------------- lib/view.js | 5 ++- 4 files changed, 76 insertions(+), 83 deletions(-) diff --git a/lib/run.js b/lib/run.js index b261540..c194936 100644 --- a/lib/run.js +++ b/lib/run.js @@ -1,6 +1,6 @@ const path = require('path'); const loader = require('./loader'); -const {readFile} = require('./utils/fs'); +const {readFile} = require('fs').promises; const {toHump} = require('./utils/str'); const {app: cfg_app, view: cfg_view, db, page, log, cache, cookie, tpl} = require('./config'); const compose = require('koa-compose'); diff --git a/lib/types.js b/lib/types.js index f60b64c..7fe05c4 100644 --- a/lib/types.js +++ b/lib/types.js @@ -1,5 +1,5 @@ const path = require('path'); -const fs = require('fs'); +const fsPromises = require('fs').promises; const {app: cfg_app} = require('./config'); const toHump = require('./utils/str').toHump; const Logger = require('./logger'); @@ -54,10 +54,13 @@ function start() { /** * createTypesFile */ -function createFile(f) { +async function createFile(f) { if(this._f == f) { return; } + if(this._f) { + delete require.cache[require.resolve(this._f)]; + } this._f = f; const f_info = f.replace(cfg_app.base_dir + path.sep, '').split(path.sep); @@ -65,21 +68,19 @@ function createFile(f) { this._APP = f_info[0]; } - const ignore = ['node_modules', 'docker', 'package-lock.json', 'types.js']; + const ignore = ['node_modules', 'docker', 'package-lock.json', 'types.js', '.git', '.gitignore']; ignore.push(path.basename(module.parent.parent.parent.filename)); cfg_app.static_dir && ignore.push(path.join(cfg_app.base_dir, cfg_app.static_dir)); - const node_list = getNodeList('.', ignore); + const node_list = await getNodeList('.', ignore); calcNodeList(node_list, this._APP); const types_tpl = require('./tpl/types'); const types_str = types_tpl.replace('__TYPES__', createTypes(node_list)).replace('__PROPERTY__', createProps(node_list)); - fs.writeFile('types.js', types_str, function(err) { - if(err) { - Logger.system('createTypes error:', err); - } else { - Logger.system('createTypes success:', path.join(cfg_app.base_dir, 'types.js')); - } + fsPromises.writeFile('types.js', types_str).then(_ => { + Logger.system('createTypes success:', path.join(cfg_app.base_dir, 'types.js')); + }).catch(err => { + Logger.system('createTypes error:', err); }); } @@ -132,27 +133,27 @@ function createProps(node_list) { } // 获取节点对象 -function getNodeList(dir, ignore=['node_modules', 'docker', 'package-lock.json']) { +async function getNodeList(dir, ignore=['node_modules', 'docker', 'package-lock.json', '.git', '.gitignore']) { const isClass = require('is-class'); - const files = fs.readdirSync(path.join(cfg_app.base_dir, dir), {withFileTypes: true}); + const files = await fsPromises.readdir(path.join(cfg_app.base_dir, dir), {withFileTypes: true}); const type_list = {}; - files.forEach(dirent => { + for(const dirent of files) { const file_name = dirent.name; const file_path = dir + '/' + file_name; const node_name = path.parse(file_name).name; const abs_path = path.join(cfg_app.base_dir, file_path); if(ignore.filter(n => abs_path.includes(n)).length) { - return; + continue; } const file_type = dirent.isFile() ? 'file' : dirent.isDirectory() ? 'dir' : ''; const regFile = /.+\.js(on)?$/.test(file_name); const regDir = !file_name.includes('.'); if(file_type == 'file' && !regFile) { - return; + continue; } if(file_type == 'dir' && !regDir) { - return; + continue; } if(file_type == 'file') { @@ -163,10 +164,10 @@ function getNodeList(dir, ignore=['node_modules', 'docker', 'package-lock.json'] // 包含语法错误时,require会出错 } } else if(file_type == 'dir') { - type_list[file_path] = {node_name, file_name, file_type, children: getNodeList(file_path, ignore)};; + type_list[file_path] = {node_name, file_name, file_type, children: await getNodeList(file_path, ignore)};; } - }); + }; return type_list; } diff --git a/lib/utils/fs.js b/lib/utils/fs.js index 82bddb0..bbfce96 100644 --- a/lib/utils/fs.js +++ b/lib/utils/fs.js @@ -1,78 +1,69 @@ const fs = require('fs'); +const fsPromises = require('fs').promises; const pt = require('path'); -const fsFun = {}; -//(读取类) -['mkdir', 'rmdir', 'readdir', 'readFile', 'copyFile', 'unlink', 'exists', 'stat'].forEach(function (item) { - fsFun[item] = function (pathname, copypath) { - return new Promise(function (resolve, reject) { - let arg = [function (err, data) { - if (item === 'exists') { - return resolve(err); - } - if (err) { - return reject(err); - } - resolve(data || true); - }]; - item === 'readFile' ? arg.unshift(copypath || 'utf8') : null; - item === 'copyFile' ? arg.unshift(copypath || '') : null; - fs[item](pathname, ...arg) - }); +// 是否存在 +const exists = async path => { + try { + await fsPromises.stat(path); + return true; + } catch(err) { + if(err.code === 'ENOENT') { + return false; + } + throw err; } -}); +} -//(写入类) -['writeFile', 'appendFile'].forEach(function (item) { - fsFun[item] = function (pathname, content, charset='utf8') { - if (typeof content !== 'string') { - content = JSON.stringify(content) - }; - return new Promise(function (resolve, reject) { - fs[item](pathname, content, charset, function(err, data){ - if (err) { - return reject(err); - } - resolve(data || ''); - }); - }); +// 是否文件 +const isFile = async path => { + try { + const stats = await fsPromises.stat(path); + return stats.isFile(); + } catch(err) { + if(err.code === 'ENOENT') { + return false; + } + throw err; } -}); - -//(判断类) -fsFun.isFileSync = (path) => {return fs.existsSync(path) && fs.statSync(path).isFile();} -fsFun.isDirSync = (path) => {return fs.existsSync(path) && fs.statSync(path).isDirectory();} +} +const isFileSync = path => { + return fs.existsSync(path) && fs.statSync(path).isFile(); +} -['isFile', 'isDir'].forEach(function (item) { - fsFun[item] = function (pathname) { - return new Promise(function (resolve, reject) { - fsFun.exists(pathname).then((result) => { - if (!result) { - resolve(result); - } else { - fsFun.stat(pathname).then((result) => { - resolve(item === 'isFile' ? result.isFile() : result.isDirectory()); - }).catch((error) => { - reject(error); - }); - } - }).catch((error) => { - reject(error); - }); - }); +// 是否目录 +const isDir = async path => { + try { + const stats = await fsPromises.stat(path); + return stats.isDirectory(); + } catch(err) { + if(err.code === 'ENOENT') { + return false; + } + throw err; } -}); +} +const isDirSync = path => { + return fs.existsSync(path) && fs.statSync(path).isDirectory(); +} -//(多级目录生成) -fsFun.mkdirs = async function (dirname) { - if(await fsFun.isDir(dirname)) { +// 生成多级目录 +const mkdirs = async function (dirname) { + if(await isDir(dirname)) { return true; } else { - if(await fsFun.mkdirs(pt.dirname(dirname))) { - await fsFun.mkdir(dirname); + if(await mkdirs(pt.dirname(dirname))) { + await fsPromises.mkdir(dirname); return true; } } } -module.exports = fsFun; \ No newline at end of file +module.exports = { + exists, + isFile, + isFileSync, + isDir, + isDirSync, + mkdirs +}; \ No newline at end of file diff --git a/lib/view.js b/lib/view.js index d85120d..d0f0009 100644 --- a/lib/view.js +++ b/lib/view.js @@ -1,5 +1,6 @@ const path = require('path'); -const {readFile, isFileSync} = require('./utils/fs'); +const {isFileSync} = require('./utils/fs'); +const {readFile} = require('fs').promises; const {app: cfg_app, view: cfg_view} = require('./config'); const {toLine} = require('./utils/str'); const Context = require('./context'); @@ -28,7 +29,7 @@ class View extends Context */ async load(template) { const file_name = this.parseTplName(template); - return await readFile(file_name); + return (await readFile(file_name)).toString(); } /**