Skip to content

Commit

Permalink
优化utils库fs工具
Browse files Browse the repository at this point in the history
  • Loading branch information
yafoo committed Feb 23, 2024
1 parent 79f0772 commit 77154fa
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 83 deletions.
2 changes: 1 addition & 1 deletion lib/run.js
Original file line number Diff line number Diff line change
@@ -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');
Expand Down
37 changes: 19 additions & 18 deletions lib/types.js
Original file line number Diff line number Diff line change
@@ -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');
Expand Down Expand Up @@ -54,32 +54,33 @@ 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);
if(f_info[0] && f_info[0] != cfg_app.common_app && !~f_info[0].indexOf('.')) {
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);
});
}

Expand Down Expand Up @@ -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') {
Expand All @@ -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;
}

Expand Down
115 changes: 53 additions & 62 deletions lib/utils/fs.js
Original file line number Diff line number Diff line change
@@ -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;
module.exports = {
exists,
isFile,
isFileSync,
isDir,
isDirSync,
mkdirs
};
5 changes: 3 additions & 2 deletions lib/view.js
Original file line number Diff line number Diff line change
@@ -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');
Expand Down Expand Up @@ -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();
}

/**
Expand Down

0 comments on commit 77154fa

Please sign in to comment.