1. #!/usr/bin/env node
  2. const readline = require('readline').createInterface({
  3. input: process.stdin,
  4. output: process.stdout,
  5. });
  6. const fs = require('fs');
  7. /**
  8. * Truncates log entries to a specified length.
  9. * @param {string} logData The log data to truncate.
  10. * @param {number} maxLength The maximum length of each log entry.
  11. * @returns {string} The truncated log data.
  12. */
  13. function truncateLog(logData, maxLength) {
  14. if (!logData) return ""; // Handle empty input
  15. return logData.length > maxLength ? logData.substring(0, maxLength) + "..." : logData;
  16. }
  17. /**
  18. * Reads log data from a file, truncates it, and writes the truncated data to a new file.
  19. */
  20. function processLogFile() {
  21. const inputFilePath = process.argv[2]; // Input file path from command line
  22. const maxLength = parseInt(process.argv[3], 10) || 100; // Max length, default to 100
  23. if (!inputFilePath) {
  24. console.error('Usage: truncate-log <input_file> <max_length>');
  25. readline.close();
  26. process.exit(1);
  27. }
  28. try {
  29. const fileContent = fs.readFileSync(inputFilePath, 'utf8');
  30. const truncatedContent = truncateLog(fileContent, maxLength);
  31. const outputFilePath = inputFilePath + '.truncated'; // Output file name
  32. fs.writeFileSync(outputFilePath, truncatedContent);
  33. console.log(`Truncated log data written to ${outputFilePath}`);
  34. } catch (error) {
  35. console.error('Error processing file:', error.message);
  36. readline.close();
  37. process.exit(1);
  38. }
  39. }
  40. readline.question('Enter the input log file path: ', (inputFilePath) => {
  41. readline.question('Enter the maximum log entry length (default: 100): ', (maxLengthStr) => {
  42. const maxLength = maxLengthStr ? parseInt(maxLengthStr, 10) : 100;
  43. processLogFile();
  44. readline.close();
  45. });
  46. });

Add your comment