const fs = require('fs').promises;
const path = require('path');
/**
* Splits a directory's data into smaller chunks for short-lived tasks.
* @param {string} directoryPath The path to the directory.
* @param {number} chunkSize The maximum size of each chunk in bytes.
* @param {function} processChunk A function to process each chunk of data. Takes the chunk data as input.
* @returns {Promise<void>} A promise that resolves when all chunks have been processed.
* @throws {Error} If the directory does not exist.
*/
async function splitDirectoryData(directoryPath, chunkSize, processChunk) {
try {
const files = await fs.readdir(directoryPath);
for (const file of files) {
const filePath = path.join(directoryPath, file);
const stats = await fs.stat(filePath);
if (stats.isFile()) {
const fileContent = await fs.readFile(filePath, { encoding: 'utf-8' }); // Read file content
const chunkLength = fileContent.length;
if (chunkLength > 0) { // Avoid processing empty files
for (let i = 0; i < chunkLength; i += chunkSize) {
const chunk = fileContent.substring(i, i + chunkSize); // Extract chunk
processChunk(chunk); // Process the chunk
}
}
}
}
} catch (error) {
if (error.code === 'ENOENT') {
throw new Error(`Directory not found: ${directoryPath}`);
}
throw error; // Re-throw other errors
}
}
module.exports = splitDirectoryData;
Add your comment