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

比如:

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

目前,我只是将文件提取到一个临时文件中,并要求这样做.

推荐答案

您可以使用http.get方法获取模块,并使用vm模块方法runInThisContextrunInNewContext在沙箱中执行它.

实例

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

在我看来,在没有替代方案的情况下,在服务器应用程序运行时内执行远程代码可能是合理的.而且只有在你信任远程服务和网络的情况下.

Node.js相关问答推荐

如何使用jq将依赖项添加到package.json中

NX无法使用缓存运行根级脚本

查询嵌套数组中的最后一个元素具有特定值的mongoDB集合中的文档

MongoDB如果文档S的字段小于另一个字段,则将该字段加一

使用ReadableStream.管道时NodeJS Crypto Hash不正确

在内存中加载安全密钥安全吗?还是每次都从文件中读取?

Sequelize、postgres和posgis:在n°;公里

为什么我的过滤器无法在我在下面编写的 Google Analytics 4 应用程序脚本代码中工作?我该如何修复它?

在 TypeScript 中正确键入 MongoDB find 方法

如何获取mongoose中单个id数据的记录

如何使用对象中的常量值验证字符串字段?

如何解决 npm install react-select failure with error : An unknown git error occurred, git@github.com :Permission denied (publickey)

nuxt:在 docker 镜像中找不到

如何为一个网站实现这 2 个网址.即 www.administrator.sitename.com 和 www.sitename.com?

等到文件上传完成的有效方法(mongoose )

如何在 Node.js 的 console.log() 中创建换行符

来自 Node-aws 的 Dynamo Local:所有操作都失败无法对不存在的表执行操作

如何判断 Node.js 中是否设置了环境变量?

npm install 给出警告,npm audit fix 不起作用

Express.js中的bodyParser.urlencoded({extended: true }))和bodyParser.json()是什么意思?