#!/usr/bin/env node
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
const fs = require('fs');
/**
* Truncates log entries to a specified length.
* @param {string} logData The log data to truncate.
* @param {number} maxLength The maximum length of each log entry.
* @returns {string} The truncated log data.
*/
function truncateLog(logData, maxLength) {
if (!logData) return ""; // Handle empty input
return logData.length > maxLength ? logData.substring(0, maxLength) + "..." : logData;
}
/**
* Reads log data from a file, truncates it, and writes the truncated data to a new file.
*/
function processLogFile() {
const inputFilePath = process.argv[2]; // Input file path from command line
const maxLength = parseInt(process.argv[3], 10) || 100; // Max length, default to 100
if (!inputFilePath) {
console.error('Usage: truncate-log <input_file> <max_length>');
readline.close();
process.exit(1);
}
try {
const fileContent = fs.readFileSync(inputFilePath, 'utf8');
const truncatedContent = truncateLog(fileContent, maxLength);
const outputFilePath = inputFilePath + '.truncated'; // Output file name
fs.writeFileSync(outputFilePath, truncatedContent);
console.log(`Truncated log data written to ${outputFilePath}`);
} catch (error) {
console.error('Error processing file:', error.message);
readline.close();
process.exit(1);
}
}
readline.question('Enter the input log file path: ', (inputFilePath) => {
readline.question('Enter the maximum log entry length (default: 100): ', (maxLengthStr) => {
const maxLength = maxLengthStr ? parseInt(maxLengthStr, 10) : 100;
processLogFile();
readline.close();
});
});
Add your comment