how to require from URL in Node.js


Question

Is there a standard way to require a Node module located at some URL (not on the local filesystem)?

Something like:

require('http://example.com/nodejsmodules/myModule.js');

Currently, I am simply fetching the file into a temporary file, and requiring that.

1
33
10/18/2011 3:02:55 PM

Accepted Answer

You can fetch module using http.get method and execute it in the sandbox using vm module methods runInThisContext and runInNewContext.

Example

var http = require('http')
  , vm = require('vm')
  , concat = require('concat-stream'); // this is just a helper to receive the
                                       // http payload in a single callback
                                       // see https://www.npmjs.com/package/concat-stream

http.get({
    host: 'example.com', 
    port: 80, 
    path: '/hello.js'
  }, 
  function(res) {
    res.setEncoding('utf8');
    res.pipe(concat({ encoding: 'string' }, function(remoteSrc) {
      vm.runInThisContext(remoteSrc, 'remote_modules/hello.js');
    }));
});

IMO, execution of the remote code inside server application runtime may be reasonable in the case without alternatives. And only if you trust to the remote service and the network between.

29
7/6/2015 11:23:42 AM

If you want something more like require, you can do this:

var http = require('http')
  , vm = require('vm')
  , concat = require('concat-stream') 
  , async = require('async'); 

function http_require(url, callback) {
  http.get(url, function(res) {
    // console.log('fetching: ' + url)
    res.setEncoding('utf8');
    res.pipe(concat({encoding: 'string'}, function(data) {
      callback(null, vm.runInThisContext(data));
    }));
  })
}

urls = [
  'http://example.com/nodejsmodules/myModule1.js',
  'http://example.com/nodejsmodules/myModule2.js',
  'http://example.com/nodejsmodules/myModule3.js',
]

async.map(urls, http_require, function(err, results) {
  // `results` is an array of values returned by `runInThisContext`
  // the rest of your program logic
});

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon