const fs = require('fs');
const zlib = require('zlib');
/**
* Formats file contents for staging with a timeout.
* @param {string} filePath - The path to the file.
* @param {number} timeout - The timeout in milliseconds.
* @returns {Promise<string|null>} - A promise that resolves with the formatted content or null if an error occurred.
*/
async function formatFileForStaging(filePath, timeout) {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const readStream = fs.createReadStream(filePath, { highWaterMark: 64 * 1024 }); // Adjust highWaterMark as needed
const gzip = zlib.createGzip();
const writeStream = fs.createWriteStream('staging_output.js'); // Output to a file
let totalBytesRead = 0;
readStream.on('data', (chunk) => {
totalBytesRead += chunk.length;
//Gzip the data
gzip.write(chunk);
});
readStream.on('end', () => {
gzip.end(() => {
// Flush the gzip stream to ensure all data is written
writeStream.write(gzip.data);
gzip.end(); // Close the gzip stream
writeStream.close(() => {
console.log(`Processed ${filePath} successfully. Total bytes read: ${totalBytesRead}`);
resolve('staging_output.js'); // Return the path to the output file
});
});
});
readStream.on('error', (err) => {
console.error(`Error reading file ${filePath}:`, err);
reject(err);
});
writeStream.on('error', (err) => {
console.error(`Error writing to file:`, err);
reject(err);
});
// Timeout implementation
setTimeout(() => {
console.warn(`Timeout reached after ${timeout}ms processing ${filePath}`);
reject(new Error(`Timeout reached after ${timeout}ms processing ${filePath}`));
}, timeout);
});
}
module.exports = formatFileForStaging;
Add your comment