Reputation: 467
I am building a cli with node, and when I had to reference the filepath of the module, I didn't understand how it worked.
From node's docs, it says that require.main === module
. What specifically do these mean ?
Upvotes: 1
Views: 3754
Reputation: 7308
From the doc ;
When a file is run directly from Node.js, require.main is set to its module. That means that you can determine whether a file has been run directly by testing
require.main === module
For a file foo.js, this will be true if run via node foo.js, but false if run by require('./foo').
So lets say you have a file called foo.js and it involves the following code;
console.log(require.main === module);
When you type " node foo.js " from terminal , you will see that it returns true. But let s say you have a second file called foo1.js and you require foo.js in this file as the following ;
var foo = require("./foo");
When you type " node foo1.js " from terminal , you will see that it returns false.
This is what this part of docs is telling.
Upvotes: 15