Almad
Almad

Reputation: 5893

Why is context inside non-interactive Function object different in node.js?

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?

Upvotes: 2

Views: 1092

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123453

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'

Upvotes: 2

Related Questions