|
| 1 | +import fs from 'fs/promises'; |
| 2 | +import path from 'path'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Reads files from a dir (recursively), mount an object with the files contents |
| 6 | + * and generates a code to be used in the worker build process. |
| 7 | + * This files mapping will be available in globalThis.\_\_FILES\_\_(worker memory). |
| 8 | + * You can use fs module to retrieve this files. |
| 9 | + * @param {string[]} dirs - paths of dirs to inject |
| 10 | + * @returns {string} - the code to be injected in bundle process. |
| 11 | + */ |
| 12 | +async function injectFilesInMem(dirs) { |
| 13 | + const result = {}; |
| 14 | + |
| 15 | + /** |
| 16 | + * Read content from files and save in the result |
| 17 | + * @param {string} dir - dir to read files; |
| 18 | + */ |
| 19 | + async function readFilesRecursively(dir) { |
| 20 | + const files = await fs.readdir(dir); |
| 21 | + |
| 22 | + await Promise.all( |
| 23 | + files.map(async (file) => { |
| 24 | + const filePath = path.join(dir, file); |
| 25 | + const stats = await fs.stat(filePath); |
| 26 | + |
| 27 | + if (stats.isDirectory()) { |
| 28 | + await readFilesRecursively(filePath); |
| 29 | + } else if (stats.isFile()) { |
| 30 | + const bufferContent = await fs.readFile(filePath); |
| 31 | + let key = filePath; |
| 32 | + if (!filePath.startsWith('/')) key = `/${filePath}`; |
| 33 | + const bufferObject = JSON.stringify(bufferContent.toString('base64')); |
| 34 | + result[key] = { content: bufferObject }; |
| 35 | + } |
| 36 | + }), |
| 37 | + ); |
| 38 | + } |
| 39 | + |
| 40 | + await Promise.all( |
| 41 | + dirs.map(async (dir) => { |
| 42 | + await readFilesRecursively(dir); |
| 43 | + }), |
| 44 | + ); |
| 45 | + |
| 46 | + const codeToInject = `globalThis.__FILES__=${JSON.stringify(result)};`; |
| 47 | + |
| 48 | + return codeToInject; |
| 49 | +} |
| 50 | + |
| 51 | +export default injectFilesInMem; |
0 commit comments