1. const fs = require('fs');
  2. const zlib = require('zlib');
  3. /**
  4. * Formats file contents for staging with a timeout.
  5. * @param {string} filePath - The path to the file.
  6. * @param {number} timeout - The timeout in milliseconds.
  7. * @returns {Promise<string|null>} - A promise that resolves with the formatted content or null if an error occurred.
  8. */
  9. async function formatFileForStaging(filePath, timeout) {
  10. return new Promise((resolve, reject) => {
  11. const startTime = Date.now();
  12. const readStream = fs.createReadStream(filePath, { highWaterMark: 64 * 1024 }); // Adjust highWaterMark as needed
  13. const gzip = zlib.createGzip();
  14. const writeStream = fs.createWriteStream('staging_output.js'); // Output to a file
  15. let totalBytesRead = 0;
  16. readStream.on('data', (chunk) => {
  17. totalBytesRead += chunk.length;
  18. //Gzip the data
  19. gzip.write(chunk);
  20. });
  21. readStream.on('end', () => {
  22. gzip.end(() => {
  23. // Flush the gzip stream to ensure all data is written
  24. writeStream.write(gzip.data);
  25. gzip.end(); // Close the gzip stream
  26. writeStream.close(() => {
  27. console.log(`Processed ${filePath} successfully. Total bytes read: ${totalBytesRead}`);
  28. resolve('staging_output.js'); // Return the path to the output file
  29. });
  30. });
  31. });
  32. readStream.on('error', (err) => {
  33. console.error(`Error reading file ${filePath}:`, err);
  34. reject(err);
  35. });
  36. writeStream.on('error', (err) => {
  37. console.error(`Error writing to file:`, err);
  38. reject(err);
  39. });
  40. // Timeout implementation
  41. setTimeout(() => {
  42. console.warn(`Timeout reached after ${timeout}ms processing ${filePath}`);
  43. reject(new Error(`Timeout reached after ${timeout}ms processing ${filePath}`));
  44. }, timeout);
  45. });
  46. }
  47. module.exports = formatFileForStaging;

Add your comment