user7898461
user7898461

Reputation:

require('.') differs from require(__filename);

Doing metaprogramming kinda stuff and I was looking into a file requiring its own exports, like so:

exports.foo = 'bar';

setTimeout(function () {
  console.log(require(__filename).foo);
},100);

it turns out the above works fine, however this doesn't seem to:

exports.foo = 'bar';

setTimeout(function () {
  console.log(require('.').foo);
},100);

does anyone know why require('.') would differ from require(__filename)?

Upvotes: 1

Views: 43

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123493

A stand-alone (or leading) period, in a module path, is a shorthand for the current folder or directory rather than the current file.

console.log(require.resolve('.') === __dirname); // true

Requiring '.' involves the process of folders as modules, that retrieves the exports from either an index.js or a configured "main" script.

Using require.resolve(), you can see the absolute path that require() will read from:

console.log(require.resolve('.'));        // e.g. "/path/to/index.js"
console.log(require.resolve(__dirname));  // e.g. "/path/to/index.js"
console.log(require.resolve(__filename)); // e.g. "/path/to/foo.js"

Upvotes: 4

Related Questions