【问题标题】:Using require in node without just code and not a file在节点中使用 require 而不是代码而不是文件
【发布时间】:2013-06-05 04:27:07
【问题描述】:

我在一个数据库中有代码,其中有不同的节点模块。像这样:

exports.hello = hello

通常,我只会使用hello = require './hello.js'。但是,因为代码存储在数据库中,所以我不能包含文件的路径。当我尝试做的时候

eval unescape hello_from_db_code 不起作用。

有没有办法在没有文件路径的情况下获得require 功能?

【问题讨论】:

  • “代码存储在数据库中”是什么意思?您能否编辑问题以使其更易于理解?
  • 按代码存储在数据库中,这意味着我将exports.hello = hello 作为字段存储在数据库而不是文件中的行中
  • 只是好奇,将 hello_from_db_code 打印到控制台会得到什么?

标签: javascript node.js coffeescript require


【解决方案1】:

我认为您不能为此使用 require。见here...

但是,您可以从数据库中读取代码,对其进行评估,然后将其导出。

无论如何,尽量避免会破坏您的模块缓存的黑客攻击。

【讨论】:

    【解决方案2】:

    如果“不起作用”是“模块未导出并且存在未定义的全局变量”,那么您可以尝试在上下文中缺少引用的情况下进行评估:

    vm = require 'vm'
    requireFromString = (str, filename) ->
      sandbox =
        module:
          exports: {}
        require: require
        __filename: filename
      vm.runInNewContext(src, sandbox, filename)
      sandbox.module.exports
    

    您可能想要添加对沙盒的额外引用,请查看module.js 中的Module.prototype._compile 函数。你也可以直接以hello = module._compile(hello_from_db_code)访问它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      • 2019-07-27
      相关资源
      最近更新 更多