Skip to content

Instantly share code, notes, and snippets.

@nkbt
Last active January 3, 2023 22:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nkbt/f6b0d071c048d755f88b46f21dd34e90 to your computer and use it in GitHub Desktop.
Save nkbt/f6b0d071c048d755f88b46f21dd34e90 to your computer and use it in GitHub Desktop.
Async require library from URL for Node
const https = require('https');
const vm = require('vm');
const requireCache = {};
const requireUrl = url => new Promise((resolve, reject) => url in requireCache ?
resolve(requireCache[url]) :
https.get(url, res => {
const result = [];
res.on('data', chunk => result.push(chunk.toString('utf-8')));
res.on('error', reject);
res.on('end', () => {
const sandbox = {};
vm.createContext(sandbox);
try {
vm.runInContext(result.join(''), sandbox);
} catch (error) {
reject(error);
return;
}
Object.assign(requireCache, {[url]: sandbox});
resolve(requireCache[url]);
});
}));
const run = async () => {
const {jsyaml} = await requireUrl('https://unpkg.com/js-yaml@3.10.0/dist/js-yaml.js');
console.log(`yaml`, jsyaml.load(`
hello: world
`));
};
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment