-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
28 lines (27 loc) · 871 Bytes
/
index.js
File metadata and controls
28 lines (27 loc) · 871 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// index.js
import https from "https";
import vm from "vm";
export async function importFromUrl(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
if (res.statusCode !== 200) {
reject(new Error(`Failed to load module, status ${res.statusCode}`));
return;
}
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () => {
try {
// Evaluate as ES module: trickier in Node.js, so for now treat as CommonJS-style
const module = { exports: {} };
const script = new vm.Script(data, { filename: url });
const context = vm.createContext({ module, exports: module.exports, require });
script.runInContext(context);
resolve(module.exports);
} catch (e) {
reject(e);
}
});
});
});
}