how to require from URL in Node.js

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

    0 dependency version (node 6+ required, you can simply change it back to ES5)

    const http = require('http'), vm = require('vm');
    
    ['http://example.com/nodejsmodules/myModule.js'].forEach(url => {
        http.get(url, res => {
            if (res.statusCode === 200 && /^text\/javascript/.test(res.headers['content-type'])) {
                let rawData = '';
                res.setEncoding('utf8');
                res.on('data', chunk => { rawData += chunk; });
                res.on('end', () => { vm.runInThisContext(rawData, url); });
            }
        });
    });
    

    It is still the asynchronous version, if sync load is the case, a sync http request module for example should be required

提交回复
热议问题