javascript - Is require in nodejs different from other functions in the global scope -


when working trough setup dynamically run code, e.g eval , friends using nodejs, encountered peculiar problem demonstrated using 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 then:

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

so seems require, understand part of global object, seems hidden when executing functions created using function constructor. unless explicitly set global object in node.

the same not apply console etc.

is require function different in context?

edit

ok, following code may shed light on 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 comments, require injected executing module. visible other functions defined in same module, in same way functions local module.

this explaned here in mdn documentation function object.

its weird though can inspect global object in nodejs repl, , require seems part of 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 following snippet shows undefined when executed file:

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

although, when executed in repl, behaves differently:

> function('console.log("typeof require: " + typeof require);')() typeof require: function 


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -