1

When working trough a setup to dynamically run code, e.g eval and its friends using nodejs, we encountered a peculiar problem demonstrated using this code snippet

console.log("typeof require: " + typeof require);

var func = new Function('console.log("typeof require: " + typeof require);');

func();
global.require = require;
func();

The output is then:

typeof require: function
typeof require: undefined
typeof require: function

So it seems that require, as I understand is always part of the global object, seems to be hidden when executing functions created using the Function constructor. Unless its explicitly set to the global object in node.

The same does not apply for console etc.

Is the require function different in that context?

EDIT

Ok, the following code may shed some light on what goes on:

function local() {

}

var func = new Function('console.log("typeof require: " + typeof require); console.log("typeof local: " + typeof local);');

function func2() {
  console.log("func2: typeof require: " + typeof require);
  console.log("func2: typeof local: " + typeof local);
}

func();
func2();

global.require = require;

func();

As mentioned in the comments, require is injected into the executing module. So its only visible to other functions defined in the same module, in much the same way as functions local to the module.

This is explaned here in the MDN documentation for the Function object.

Its weird though that you can inspect the global object in the nodejs REPL, and require seems to be part of the global object:

$ node
> global
{ global: [Circular],
  process: 
   process {
...
        '/home/node_modules',
        '/node_modules' ] },
  require: 
   { [Function: require]
     resolve: [Function],
     main: undefined,
     extensions: { '.js': [Function], '.json': [Function], '.node': [Function] },
     registerExtension: [Function],
     cache: {} },
  _: [Circular] }

But the following snippet shows undefined when executed from a file:

console.log("typeof global.require: " + typeof global.require);

Although, when executed in the REPL, it behaves differently:

> Function('console.log("typeof require: " + typeof require);')()
typeof require: function
Ernelli
  • 3,960
  • 3
  • 28
  • 34
  • 3
    It's not implicitly global, IIRC it's implicitly injected into all modules. (I might be wrong though) – Madara's Ghost Feb 08 '16 at 14:16
  • 1
    `require` is indeed created for each module loaded, [as can be seen here](https://github.com/nodejs/node/blob/7c603280024de60329d5da283fb8433420bc6716/lib/internal/module.js#L7-L8). – Bartek Banachewicz Feb 08 '16 at 16:47
  • maybe have a look at [In what scope are module variables stored in node.js?](http://stackoverflow.com/q/15406062/1048572) – Bergi Feb 08 '16 at 17:45

0 Answers0