Untitled

 avatar
unknown
javascript
5 months ago
1.9 kB
5
Indexable
const fs = require('fs');
const readline = require('readline');
const path = require('path');

// Define input and output file paths
const logFilePath = path.join(__dirname, 'Player.log'); // Replace 'log.txt' with your log file's name
const outputFilePath = path.join(__dirname, 'analytics.json');

// Create a readable stream for the log file
const fileStream = fs.createReadStream(logFilePath);

// Create an interface to read the file line by line
const rl = readline.createInterface({
  input: fileStream,
  crlfDelay: Infinity
});

// Prepare the write stream to output results
const outputStream = fs.createWriteStream(outputFilePath);
outputStream.write('[\n'); // Start JSON array in the output file

let isFirst = true;

// Helper function to convert nested strings to JSON if possible
const tryParseNestedJSON = (obj, key) => {
  if (typeof obj[key] === 'string') {
    try {
      obj[key] = JSON.parse(obj[key]);
    } catch (err) {
      // Leave the property as a string if it can't be parsed
    }
  }
};

rl.on('line', (line) => {
  try {
    // Attempt to parse each line as JSON
    const parsed = JSON.parse(line);

    // Check if the line contains the category 'Analytics'
    if (parsed.category === 'Analytics') {
      // Check and fix 'responseString' or 'responseValue' if they exist
      if (parsed.data) {
        tryParseNestedJSON(parsed.data, 'responseString');
        tryParseNestedJSON(parsed.data, 'responseValue');
      }

      if (!isFirst) {
        outputStream.write(',\n'); // Add a comma and newline between JSON objects
      }
      outputStream.write(JSON.stringify(parsed, null, 2));
      isFirst = false;
    }
  } catch (err) {
    // Ignore lines that cannot be parsed as JSON
  }
});

rl.on('close', () => {
  outputStream.write('\n]\n'); // Close JSON array
  outputStream.end();
  console.log('Processing completed. Extracted objects saved to:', outputFilePath);
});
Editor is loading...
Leave a Comment