how to require from URL in Node.js

前端 未结 6 2401
一个人的身影
一个人的身影 2020-11-28 07:54

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/node         


        
6条回答
  •  一生所求
    2020-11-28 08:29

    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.

提交回复
热议问题