Why is the context inside a non-integrated function object different from node.js?

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

When I try to do this in the 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 same code in a file, they tell me that the require function is not available:

 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 it?

Also, this tells me that I don't know something about node.js contexts / scopes. What is it?

+1
source share
1 answer

The problem is the scope.

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

So, to define a function so that require in closure , you will need to use the function statement / keyword :

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

Or, -> operator in CoffeeScript:

 f = -> require 'crypto' 
+2
source

All Articles