Skip to content

Instantly share code, notes, and snippets.

@svdoever
Last active August 7, 2018 21:52
Show Gist options
  • Save svdoever/aebdbc6acf0bd15e354c18af9ed1bd47 to your computer and use it in GitHub Desktop.
Save svdoever/aebdbc6acf0bd15e354c18af9ed1bd47 to your computer and use it in GitHub Desktop.
NodeJS: load multiple bundles from local and remote (http, https)
// bundleConfiguration is a javascript object in the following format:
// let bundleConfiguration = {
// default: './server-bundle',
// pwa: './server-bundle',
// pwaremote: 'http://myserver.com/server-bundle.js'
// };
// bundles is an empty onbject, i.e. let bundles = {};
// the function returns an array of promises to wait for:
// bundleLoaderPromises = loadBundles(bundlesConfiguration, bundles);
// Promise.all(bundleLoaderPromises).then(() => {
// .... do your thing ...
// }).catch(reason => {
// console.error(reason.message);
// process.exit(1);
// });
function loadBundles(bundlesConfiguration, bundles) {
const http = require('http');
const https = require('https');
let bundleLoaderPromises = [];
for (let bundleName in bundlesConfiguration) {
let bundlePath = bundlesConfiguration[bundleName];
if (bundlePath.startsWith("http")) {
let client = http;
if (bundlePath.toString().indexOf("https") === 0){
client = https;
}
const promise = new Promise((resolve, reject) => {
request = client.get(bundlePath, res => {
if (res.statusCode === 200 && res.headers['content-type'].includes('javascript')) {
let rawData = '';
res.setEncoding('utf8');
res.on('data', chunk => { rawData += chunk; });
res.on('end', () => {
var m = new module.constructor();
m._compile(rawData, bundlePath);
bundles[bundleName] = m.exports;
console.log(`Loaded remote bundle '${bundleName}' from path '${bundlePath}'`);
resolve();
});
} else {
reject(new Error(`Failed to load remote bundle '${bundleName}' from path '${bundlePath}' (${res.statusCode};content-type=${res.headers['content-type']})`));
}
});
request.on('error', reject);
request.end();
});
bundleLoaderPromises.push(promise);
} else {
try {
bundles[bundleName] = require(bundlePath);
console.log(`Loaded local bundle '${bundleName}' from path '${bundlePath}'`);
} catch(error) {
console.error(new Error(`Failed to load local bundle '${bundleName}' from path '${bundlePath}'. Error: ${error.message}`));
process.exit(1);
}
}
}
return bundleLoaderPromises;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment