2

I'd like to create a function from string that requires another module (don't ask).

When I try to do that in node interactive shell, everything is fine and dandy:

> f = new Function("return require('crypto')");
[Function]
> f.call()
{ Credentials: [Function: Credentials],
  (...)
  prng: [Function] }

However, when I put the exact same code in file, I am told that require function is not avaliable:

israfel:apiary almad$ node test.coffee 

undefined:2
return require('crypto')
       ^
ReferenceError: require is not defined
    at eval at <anonymous> (/tmp/test.coffee:1:67)
    at Object.<anonymous> (/tmp/test.coffee:2:3)
    at Module._compile (module.js:446:26)
    at Object..js (module.js:464:10)
    at Module.load (module.js:353:31)
    at Function._load (module.js:311:12)
    at Array.0 (module.js:484:10)
    at EventEmitter._tickCallback (node.js:190:38)

How to fix that?

Also, it tells me I do not know something about node.js contexts/scopes. What is that?

1 Answer 1

2

The issue is scope.

The argument to new Function() is being evaluated in the global scope. Node, however, only defines require as a global for its interactive mode/shell. Otherwise, it executes each module within a closure where require, module, exports, etc. are defined as local variables.

So, to define the function so that require is in scope (closure), you'll have to use the function operator/keyword:

f = function () { return require('crypto'); }

Or, the -> operator in CoffeeScript:

f = -> require 'crypto'
Sign up to request clarification or add additional context in comments.

2 Comments

So there is no way to execute Function instance in a global scope?
@Almad You can define a global reference to the function, f. But, the body of the function has to be evaluated within the closure to have require in scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.