app-lib-trans-storage
Version:
文本文件进行转换JSON存储,常用于exec执行文件场景
99 lines (90 loc) • 3.9 kB
JavaScript
const path = require("path");
const { readFileSync, isExistFile,resolve, isExistDir, writeFileSyncAndCreate, readdirSync,getRootPath } = require("app-lib-node");
const { log } = require("app-lib-log");
const BUILD_PATH = "./src/trans-static";
const FILE_PATH = "./static/"; // 默认文件写入位置
const BASE_PATH = "./static/store.json"; // 默认文件存储位置
/**
* 将文件转换为JSON进行存储
*
* @param {array} filePaths 多个文件转换了路径
* @param {string} [storagePath='./static/store.json'] 存储的文件路径名称 一般为json 便捷处理
* @returns {array} 返回文件读取的JSON内容
*
* * example
* ```
* filesToJson([path.resolve(__dirname,`./b.ps1`),path.resolve(__dirname,`./a.ps1`)]
* ```
* @function
*/
const filesToJson = (filePaths = [], storagePath = BASE_PATH) => {
let storageDatas = filePaths.map(filePath => {
if (!isExistFile(filePath)) {
log.men("不存在文件文件", path.resolve(filePath));
return null;
} else {
let data = readFileSync(filePath);
return { name: filePath.split('\\').pop(), content: data };
}
}).filter(v => !!v)
// 写入文件
storageDatas.length && writeFileSyncAndCreate(storagePath, JSON.stringify(storageDatas, null, 2));
return storageDatas;
}
/**
* 存储文件转换为文件
* @param {string} [storagePath='./static/store.json'] 存储文件位置
* @param {string} [basePath ='./static/'] 每个文件存储路径
* @returns {array} 所有存储的文件路径
* @function
*/
const pathToFile = (storagePath = BASE_PATH, basePath = FILE_PATH) => {
if (!isExistFile(storagePath)) {
return log.men("不存在文件文件", storagePath);
}
return jsonToFile(JSON.parse(readFileSync(storagePath)), basePath);
}
/**
* 存储文件转换为文件
* @param {array} [fileDatas='[]'] 存储数据
* @param {string} [basePath ='./static/'] 每个文件存储路径
* @param {boolean} [isForce=false] 是否强制写入 默认false
* @returns {array} 所有存储的文件路径
* @function
*/
const jsonToFile = (fileDatas = [], basePath = FILE_PATH, isForce = false) =>
fileDatas.map(({ name, content }) => {
// let filePath = path.resolve(basePath || '', name);
let filePath = getRootPath(path.join(basePath || '', name));
// console.log(getRootPath(),filePath,resolve(filePath));
// 非强制时候 不是每次都会写入 避免频繁的磁盘抄作 只有第一次会写入
// 后续可以考虑按照版本来进行判断是否要清理缓存 避免静态文件未更新的情况 目前不需要
if (!isForce && isExistFile(filePath)) {
// log.md("文件已经存在,不再进行覆写",filePath)
return filePath;
}
writeFileSyncAndCreate(filePath, content)
return filePath
})
/**
* 构建文件夹
* * 注意 所有文件路径是平级 不支持嵌套
* @param {string} buildDirPath=src/trans-static 构建的文件夹路径
* @param {string} [storagePath=./static/store.json] 存储路径
*/
const buildDirFiles = (buildDirPath = BUILD_PATH, storagePath = BASE_PATH) => {
// 扫描
if (!isExistDir(buildDirPath)) {
return log.md("不存在静态文件目录", buildDirPath);
}
// 只用文件 文件夹不在范围 也不支持嵌套
let filePaths = readdirSync(buildDirPath).filter(v => !isExistDir(path.resolve(buildDirPath, v)))
.map(v=>path.resolve(buildDirPath,v));
return filesToJson(filePaths, storagePath)
}
module.exports = {
filesToJson, // 作为工具使用
pathToFile, // 存储路径转换为文件
jsonToFile, // 常用
buildDirFiles, // 编译目录
}