@jzinfo/create-project
Version:
前端项目脚手架工具
106 lines (94 loc) • 2.46 kB
JavaScript
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const execSync = require('child_process').execSync;
/**
* 遍历给定目录下的指定文件
* @param {String} root 根目录
* @param {Function} filter 过滤器
* @returns {[String]}
*/
function travelPaths(root, filter) {
let paths = [];
const entries = fs.readdirSync(root, { withFileTypes: true });
let filepath;
for (const entry of entries) {
filepath = path.join(root, entry.name);
if (entry.isFile() && filter(filepath)) {
paths.push(filepath);
} else if (entry.isDirectory()) {
paths.push(...travelPaths(filepath, filter));
}
}
return paths;
}
/**
* 替换文件内容
* @param filePath 文件路径
* @param sourceRegx 正则
* @param targetStr 目标文本
*/
function replaceFileContentSync(filePath, sourceRegx, targetStr) {
const data = fs.readFileSync(filePath)
let content = data.toString('utf8')
content = content.replace(sourceRegx, targetStr)
fs.writeFileSync(filePath, content)
}
/**
* 检测是否是图片文件(目前 tinypng.com 只支持 png/jpg/jpeg 类型的图片)
* @param file
*/
function isImage(file) {
return ['.png', '.jpg', '.jpeg'].includes(path.extname(file))
}
/**
* 计算文件md5
* @param file
* @returns {string}
*/
function fileHash(file) {
const buffer = fs.readFileSync(file)
return crypto.createHash('md5').update(buffer).digest('hex')
}
/**
* 解析缓存
* @param {string} cacheFile 缓存文件位置
*/
function resolveCache(cacheFile) {
let cache = []
if (fs.existsSync(cacheFile)) {
const content = fs.readFileSync(cacheFile).toString('utf8')
if (content) {
cache.push(...JSON.parse(content))
}
}
return cache
}
/**
* 覆盖缓存
* @param data 缓存数据
* @param {string} cacheFile 缓存文件位置
*/
function overrideCache(data, cacheFile) {
// 检查缓存文件是否存在
if (!fs.existsSync(cacheFile)) {
fs.mkdirSync(path.dirname(cacheFile), {recursive: true})
}
fs.writeFileSync(cacheFile, data, {flag: 'w'})
}
/**
* 同步执行命令
* @param cmd
*/
function execCmdSync(cmd) {
execSync(cmd, {encoding: 'utf8', stdio: "inherit"})
}
module.exports = {
travelPaths,
isImage,
fileHash,
resolveCache,
overrideCache,
replaceFileContentSync,
execCmdSync,
}