title: Is require in nodejs different from other functions in the global scope
body: <p>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</p>
  
  <pre><code>console.log("typeof require: " + typeof require);
  
  var func = new Function('console.log("typeof require: " + typeof require);');
  
  func();
  global.require = require;
  func();
  </code></pre>
  
  <p>The output is then:</p>
  
  <pre><code>typeof require: function
  typeof require: undefined
  typeof require: function
  </code></pre>
  
  <p>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.</p>
  
  <p>The same does not apply for console etc.</p>
  
  <p>Is the require function different in that context?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Ok, the following code may shed some light on what goes on:</p>
  
  <pre><code>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();
  </code></pre>
  
  <p>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.</p>
  
  <p>This is explaned here in the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" rel="nofollow">MDN documentation</a> for the Function object.</p>
  
  <p>Its weird though that you can inspect the global object in the nodejs REPL, and require seems to be part of the global object:</p>
  
  <pre><code>$ node
  &gt; 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] }
  </code></pre>
  
  <p>But the following snippet shows undefined when executed from a file:</p>
  
  <pre><code>console.log("typeof global.require: " + typeof global.require);
  </code></pre>
  
  <p>Although, when executed in the REPL, it behaves differently:</p>
  
  <pre><code>&gt; Function('console.log("typeof require: " + typeof require);')()
  typeof require: function
  </code></pre>