how to require from URL in Node.js

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

    
      const localeSrc = 'https://www.trip.com/m/i18n/100012631/zh-HK.js';
      const http = require('http');
      const vm = require('vm');
      const concat = require('concat-stream');
      http.get(
        localeSrc,
        res => {
          res.setEncoding('utf8');
          res.pipe(
            concat({ encoding: 'string' }, remoteSrc => {
              let context = {};
              const script = new vm.Script(remoteSrc);
              script.runInNewContext(context);
              console.log(context);
            }),
          );
        },
        err => {
          console.log('err', err);
        },
      );
    

提交回复
热议问题