// 将.log文件转成json,删除不必要的字段(未删干净)
const fs = require('fs');
const path = require('path');
const sourceDir = './source'; // 源文件目录路径
const targetDir = './target_directory'; // 目标文件目录路径
// 遍历指定目录下的所有文件,并执行回调函数
function traverseDir(dir, callback) {
fs.readdirSync(dir).forEach(file => {
const filePath = path.join(dir, file);
if (fs.statSync(filePath).isDirectory()) {
const subDir = path.join(targetDir, filePath.substring(sourceDir.length + 1));
if (!fs.existsSync(subDir)) {
fs.mkdirSync(subDir);
}
traverseDir(filePath, callback);
} else {
callback(filePath);
}
});
}
// 删除指定文件中符合条件的字符串
function deleteStringInFile(filePath) {
try {
let content = fs.readFileSync(filePath, 'utf8');
const regex = /2023-(.*?)content:/gs;
content = content.replace(regex, ',');
const targetFilePath = path.join(targetDir, filePath.substring(sourceDir.length + 1)) + '.json';
fs.writeFileSync(targetFilePath, content, 'utf8');
console.log(`Successfully processed file: ${filePath}`);
} catch (err) {
console.error(`Failed to process file ${filePath}: ${err.message}`);
}
}
// 遍历指定目录下的所有文件,并删除符合条件的字符串
function deleteStringInDir(dir) {
traverseDir(dir, deleteStringInFile);
}
// 示例:删除 D:\test 目录及其子目录下所有完整匹配的字符串
deleteStringInDir(sourceDir);