how to require from URL in Node.js

前端 未结 6 2423
一个人的身影
一个人的身影 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:45

    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
    });
    

提交回复
热议问题