itoolbox-cli
Version:
iToolBox CLI 工具,用于创建扩展,打包扩展.
100 lines (90 loc) • 2.09 kB
JavaScript
const fs = require('fs');
// 系统资源查找库
const which = require('which');
// 获取当前的系统语言
const osLocale = require('os-locale');
const { EN_TIP, ZH_TIP } = require('../constants/i18n');
/**
* 判断是否存在文件
* @param {String} filePath 文件夹地址
*/
const isHaveFile = (filePath) => {
return fs.existsSync(filePath);
};
/**
* 判断文件夹是否存在
* @param {String} folderPath 文件夹地址
*/
const isHaveFolder = (folderPath) => {
return fs.existsSync(folderPath);
};
/**
* 获取文件内容
* @param {String} filePath 文件地址
*/
const readFile = (filePath) => {
const isHave = isHaveFile(filePath);
if (isHave) {
return fs.readFileSync(filePath, { encoding: 'utf-8' });
} else {
return false;
}
};
/**
* 复制文件
* @param {String} filePath 文件地址
* @param {String} targetPath 目标文件地址
*/
const copyFile = (filePath, targetPath) => {
fs.copyFileSync(filePath, targetPath);
};
/**
* 写文件
* @param {String} filePath 文件地址
* @param {String} content 内容
* @param {Function} callback 回调函数
*/
const writeFile = (filePath, content, callback) => {
fs.writeFile(filePath, content, { encoding: 'utf-8' }, (err) => {
if (err) {
console.log(err);
callback && callback(false);
} else {
callback && callback(true)
}
});
};
/**
* 查找可使用的 npm 类型
*/
const findNpm = () => {
const npms = ['cnpm', 'yarn', 'npm'];
for (var i = 0; i < npms.length; i++) {
try {
which.sync(npms[i]);
return npms[i];
} catch (e) {
}
}
throw new Error('请先安装 npm');
};
/**
* 获取本地化的提示信息
*/
const getLocalTip = () => {
const language = osLocale.sync();
if (language === 'zh-CN') {
return ZH_TIP;
} else {
return EN_TIP;
}
};
module.exports = {
isHaveFile,
isHaveFolder,
readFile,
copyFile,
writeFile,
findNpm,
getLocalTip,
};