Skip to content

Commit 1555c98

Browse files
feat: Create injectFilesInMem util
1 parent cab1095 commit 1555c98

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

lib/utils/index.js

+2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import getUrlFromResource from './getUrlFromResource/index.js';
1717
import generateWebpackBanner from './generateWebpackBanner/index.js';
1818
import relocateImportsAndRequires from './relocateImportsAndRequires/index.js';
1919
import getExportedFunctionBody from './getExportedFunctionBody/index.js';
20+
import injectFilesInMem from './injectFilesInMem/index.js';
2021

2122
export {
2223
copyDirectory,
@@ -38,4 +39,5 @@ export {
3839
VercelUtils,
3940
generateWebpackBanner,
4041
relocateImportsAndRequires,
42+
injectFilesInMem,
4143
};

lib/utils/injectFilesInMem/index.js

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import injectFilesInMem from './injectFilesInMem.utils.js';
2+
3+
export default injectFilesInMem;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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

Comments
 (0)