1. const fs = require('fs').promises;
  2. const path = require('path');
  3. /**
  4. * Splits a directory's data into smaller chunks for short-lived tasks.
  5. * @param {string} directoryPath The path to the directory.
  6. * @param {number} chunkSize The maximum size of each chunk in bytes.
  7. * @param {function} processChunk A function to process each chunk of data. Takes the chunk data as input.
  8. * @returns {Promise<void>} A promise that resolves when all chunks have been processed.
  9. * @throws {Error} If the directory does not exist.
  10. */
  11. async function splitDirectoryData(directoryPath, chunkSize, processChunk) {
  12. try {
  13. const files = await fs.readdir(directoryPath);
  14. for (const file of files) {
  15. const filePath = path.join(directoryPath, file);
  16. const stats = await fs.stat(filePath);
  17. if (stats.isFile()) {
  18. const fileContent = await fs.readFile(filePath, { encoding: 'utf-8' }); // Read file content
  19. const chunkLength = fileContent.length;
  20. if (chunkLength > 0) { // Avoid processing empty files
  21. for (let i = 0; i < chunkLength; i += chunkSize) {
  22. const chunk = fileContent.substring(i, i + chunkSize); // Extract chunk
  23. processChunk(chunk); // Process the chunk
  24. }
  25. }
  26. }
  27. }
  28. } catch (error) {
  29. if (error.code === 'ENOENT') {
  30. throw new Error(`Directory not found: ${directoryPath}`);
  31. }
  32. throw error; // Re-throw other errors
  33. }
  34. }
  35. module.exports = splitDirectoryData;

Add your comment