Node provides a mechanism to determine if code in a module was executed directly from the Node process, e.g. like this:
$ node file.js
We can also tell if the code was executed during import using the require() function.
The technique is to check the condition:
require.main === module
The following example shows the full details.
A module and a main script are below.
example-module.js
// Determine if run directly
// i.e. with `node file.js`.
if (require.main === module) {
console.log("Run directly");
}
else {
console.log("Run via require()");
}
main-script.js
require("./example-module.js");
console.log("Main script");
Executing the module file directly:
$ node example-module.js
Result:
Run directly
Executing the main script, which requires the module:
$ node main-script.js
Result:
Run via require() Main script
This logic can be used to run some code only if running directly with node but not when including the file in other contexts, e.g. for test suites.
