0

I have code in a database that has different node modules in it. Like this:

exports.hello = hello

Normally, I would just use hello = require './hello.js'. However, becuase the code is stored in the db, I can't include a path to the file. When I try and do

eval unescape hello_from_db_code doesn't work.

Is there a way to get the require functionality without having a path to the file?

4

2 回答 2

1

If 'doesn't work' is 'module is not exported and there are undefined globals' then you can try to eval with missing references in the context:

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

You may want to add extra references to sandbox, look at Module.prototype._compile function in module.js. Also you can access it directly as hello = module._compile(hello_from_db_code)

于 2013-06-09T10:25:21.397 回答
1

i don't think you can use require for this. see here...

however, you can read the code from the db, eval it, and then export it.

anyway, try avoiding hacks that will trash your modules cache.

于 2013-06-09T10:30:41.023 回答