Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  156] [ 7]  / answers: 1 / hits: 66182  / 13 Years ago, tue, october 18, 2011, 12:00:00

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.


More From » node.js

 Answers
2

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.


[#89552] Monday, October 17, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
quentinaveryb

Total Points: 102
Total Questions: 100
Total Answers: 93

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
quentinaveryb questions
Thu, Aug 6, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;