You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

103 lines
2.3 KiB

const fs =require('fs');
/**
* 新建目录
* @param {*} dir 目录路径
*/
function mkdir(dir){
fs.mkdirSync(dir,{recursive: true});
}
/**
* 删除目录
* @param {*} dir 目录
*/
function rm(dir){
fs.rmSync(dir,{recursive: true});
}
function cp(src,target){
fs.cpSync(src,target,{recursive: true});
}
/**
* 解析 json 格式文件
* @param {*} src 文件路径
* @returns javascript 对象
*/
function parseJson(src){
return JSON.parse(fs.readFileSync(src).toString());
}
/**
* 替换文件中的字符串
* @param {*} filePath 文件路径
* @param {*} repalcer 替换字符 Map(key:需要替换的字符串,value:替换后的字符串)
*/
function replaceAll(filePath,repalcer){
let content =fs.readFileSync(filePath,{encoding:'utf-8'});
if(repalcer){
for(const key in repalcer){
content =content.replaceAll(key,repalcer[key]);
}
}
fs.writeFileSync(filePath,content);
}
/**
* 合并两个对象
* @param {*} target 目标对象
* @param {*} source 源对象
* @returns 合并后的对象
*/
function mergeObject(target, source) {
if (source && target) {
for (const property in source) {
const value = source[property];
if (typeof value === 'object' && !Array.isArray(value)) {
if (target[property] === null || typeof target[property] === 'undefined') {
target[property] = {};
}
mergeObject(target[property], value);
} else {
if (value !== null && typeof value !== 'undefined') {
target[property] = value;
}
}
}
}
return target;
}
/**
* 合并 json 文件
* @param {*} targetPath 目标文件
* @param {*} srcPath 源文件
* @param {*} includeProperties 包含的需要合并的属性列表
*/
function mergeJsonFile(targetPath,srcPath,includeProperties){
const target =parseJson(targetPath);
const source =parseJson(srcPath);
if(includeProperties && includeProperties.length>0){
for(const property of includeProperties){
if(target[property]){
mergeObject(target[property],source[property]);
}else{
target[property] =source[property];
}
}
}else{
mergeObject(target,source);
}
fs.writeFileSync(targetPath, JSON.stringify(target, null, ' '));
}
module.exports = {
mkdir,
rm,
cp,
parseJson,
replaceAll,
mergeObject,
mergeJsonFile,
};