nodejs将console.log保存到log.txt文档中(electron工具)
txtConsole.js
const { app } = require('electron');
const fs = require('fs');
const moment = require('moment');
const mainData = require('./mainData');
//electron 软件根目录
const rootPath = path.dirname(app.getPath('exe'));
const txtConsole = {
log(p1 = '', p2 = '', p3 = '', p4 = '', p5 = '') {
const logPath = `${rootPath}/log.txt`;
try {
//创建config文件
if (!fs.existsSync(logPath)) {
//新建文件
fs.writeFileSync(logPath, '');
}
//追加到log文件
fs.appendFileSync(
logPath,
`\r\n ${moment().format('Y-MM-DD HH:mm:ss')} | ${p1} ${p2} ${p3} ${p4} ${p5}`,
);
console.log(p1, p2, p3, p4, p5);
} catch (err) {
console.log('txtConsole: ', err);
}
},
//清除日志 在app.js内进入执行
clearLog() {
const logPath = `${rootPath}/log.txt`;
try {
if (fs.existsSync(logPath)) {
let stat = (fs.statSync(logPath)?.size || 1) / 1024;
txtConsole.log(`当前log文件大小:${parseInt(stat)}KB`);
if (parseInt(stat) > 1024) fs.unlinkSync(logPath);
}
} catch (err) {
console.log(err);
}
},
}; //日志文件
module.exports = txtConsole;
调用
txtConsole.log(1,2,3);