const fs = require('fs');
const readline = require('readline');
const file = readline.createInterface({
input: fs.createReadStream('input.log'),
output: process.stdout,
terminal: false
});
file.on('line', (line) => {
if (line.includes('warning')) {
fs.appendFile('output.log', '\r\n\r\n', err => {
if (err) {
console.error(err);
}
});
} else if (line.includes('error')) {
console.log(line)
fs.appendFile('output.log', line "\r\n", err => {
if (err) {
console.error(err);
}
});
}
});
The code works but I need to avoid putting the two newlines when "warning" is on the last line of the file
CodePudding user response:
You could try like this. This code won't save the last warning line at all:
const fs = require('fs');
const readline = require('readline');
const file = readline.createInterface({
input: fs.createReadStream('input.log'),
output: process.stdout,
terminal: false,
});
let lastLine = '';
file.on('line', (line) => {
if (lastLine) {
fs.appendFile('output.log', lastLine, (err) => {
if (err) {
console.error(err);
}
});
}
if (line.includes('warning')) {
console.log(line);
lastLine = '\r\n\r\n';
} else if (line.includes('error')) {
console.log(line);
lastLine = line '\r\n';
}
else {
lastLine = null;
}
});
// only write last line if it was error
file.on('close', () => {
if (!lastLine || lastLine === '\r\n\r\n') {
return;
}
fs.appendFile('output.log', lastLine, (err) => {
if (err) {
console.error(err);
}
});
});