crootfast
Version:
大前端工程化命令行脚手架
120 lines (109 loc) • 3.41 kB
JavaScript
const fs = require('fs');
const path = require('path');
/**
* 异步创建文件和目录。
* @param {string} filePath 要创建的文件路径。
* @param {string} content 要写入文件的内容。
* @param {boolean} append 是否追加内容到文件。
*/
async function SyncCreateFile(filePath, content, append = false) {
return new Promise((resolve, reject) => {
try {
// 获取文件所在目录
const dir = path.dirname(filePath);
// 检查目录是否存在,如果不存在则递归创建
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// 根据 append 参数决定是覆盖还是追加内容
const writeFlag = append ? 'a' : 'w';
// 异步写入/追加内容到文件
fs.writeFile(filePath, content, { flag: writeFlag }, err => {
if (err) {
reject(err)
throw err;
}
console.log(`File ${append ? 'updated' : 'created'} at ${filePath}`);
resolve();
});
} catch (error) {
console.error('An error occurred:', error);
reject(error)
}
});
}
// 示例使用
// SyncCreateFile('/a/b/c/t.txt', 'Hello, world!\n', true);
/**
* 同步创建一个目录。
* @param {string} dirPath 要创建的目录路径。
*/
function SyncCreateDirectory(dirPath) {
try {
fs.mkdirSync(dirPath, { recursive: true });
console.log(`Directory created at ${dirPath}`);
} catch (error) {
console.error('An error occurred:', error);
}
}
// 示例使用
// createDirectorySync('/path/to/your/new/directory');
/**
* 异步读取文件内容。
* @param {string} filePath 文件的路径。
* @param {function} callback 回调函数,接受两个参数:error和data。
*/
function readFileContents(filePath = "") {
return new Promise((resolve, reject) => {
fs.readFile(filePath, { encoding: 'utf8' }, (err, data) => {
if (err) {
return reject(err);
// return callback(err, null);
}
resolve(data);
// callback(null, data);
});
})
}
/**
* 替换文件中的指定标记为对应的值。
*
* @param {string} filePath 文件的路径。
* @param {Array<{tag: string, value: string}>} replacements 替换的标记和值。
*/
function replaceTagsInFile(filePath, replacements) {
return new Promise((resolve, reject) => {
// 确保文件路径是绝对路径
const absolutePath = path.resolve(filePath);
// 读取文件内容
fs.readFile(absolutePath, 'utf8', (err, data) => {
if (err) {
reject(err);
console.error('读取文件时发生错误:', err);
return;
}
// 遍历所有替换项,并更新数据
let updatedContent = data;
replacements.forEach(replacement => {
updatedContent = updatedContent.replace(new RegExp(replacement.tag, 'g'), replacement.value);
// console.log('replacement', updatedContent, replacement);
});
// 将更新后的内容写回文件
fs.writeFile(absolutePath, updatedContent, 'utf8', (err) => {
if (err) {
reject(err);
console.error('写入文件时发生错误:', err);
return;
}
resolve();
console.log('文件已成功更新!');
});
});
});
}
module.exports = {
SyncCreateFile,
SyncCreateDirectory,
readFileContents,
replaceTagsInFile
};