Skip to content

Instantly share code, notes, and snippets.

@rmg
Created January 27, 2014 19:54
Show Gist options
  • Save rmg/8656027 to your computer and use it in GitHub Desktop.
Save rmg/8656027 to your computer and use it in GitHub Desktop.
Behaviour of Node's require() under repl, module, and -e.
$ cat req.js
console.log('global.require', global.require)
console.log('bare require', require)
console.log('global.require === require', global.require === require)
$ node req.js
global.require undefined
bare require function require(path) {
return self.require(path);
}
global.require === require false
$ node -e "$(cat req.js)"
global.require function require(path) {
return self.require(path);
}
bare require function require(path) {
return self.require(path);
}
global.require === require true
$ node < req.js
global.require function require(path) {
return self.require(path);
}
bare require function require(path) {
return self.require(path);
}
global.require === require true
@bajtos
Copy link

bajtos commented Jan 27, 2014

The global object in V8 is of different opinion:

node-inspector:protocol:v8-debug request: {
  "seq":15,
  "type":"request",
  "command":"evaluate",
  "arguments":{"expression":"require","global":true}
} +210ms

node-inspector:protocol:v8-debug response {
  "seq":30,
  "request_seq":15,
  "type":"response",
  "command":"evaluate",
  "success":false,
  "message":"ReferenceError: require is not defined","running":true
}

And here is the cause: lib/module.js#L407-L415

      sandbox.require = require;
      sandbox.exports = self.exports;
      sandbox.__filename = filename;
      sandbox.__dirname = dirname;
      sandbox.module = self;
      sandbox.global = sandbox;  /** OOOK! **/
      sandbox.root = root;

      return runInNewContext(content, sandbox, { filename: filename });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment