如何从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.