如何从Node.js中的URL要求 [英] how to require from URL in Node.js

查看:97
本文介绍了如何从Node.js中的URL要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有标准方法要求Node模块位于某个URL(而不是本地文件系统)?

Is there a standard way to require a Node module located at some URL (not on the local filesystem)?

类似于:

require('http://example.com/nodejsmodules/myModule.js');

目前,我只是将文件提取到一个临时文件中,并要求它。

Currently, I am simply fetching the file into a temporary file, and requiring that.

推荐答案

您可以使用 http.get 方法并使用 vm 模块方法 runInThisContext runInNewContext

You can fetch module using http.get method and execute it in the sandbox using vm module methods runInThisContext and runInNewContext.

示例

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,在没有替代方案的情况下,在服务器应用程序运行时内执行远程代码可能是合理的。并且只有当您信任远程服务和网络之间时。

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.

这篇关于如何从Node.js中的URL要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆