How can I detect whether my Node.JS file was called using SH:node path-to-file
or JS:require('path-to-file')
?
This is the Node.JS equivalent to my previous question in Perl: How can I run my Perl script only if it wasn't loaded with require?
When a file is run directly from Node. js, require. main is set to its module. That means that it is possible to determine whether a file has been run directly by testing require. main === module .
The require module, which appears to be available on the global scope — no need to require('require') . The module module, which also appears to be available on the global scope — no need to require('module') .
What is a CLI tool? CLI tools allow you to run certain tasks or operations right from your terminal or command line prompt. They can be built using different programming languages, and one way to create a CLI tool is by using Node. js.
1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
if (require.main === module) { console.log('called directly'); } else { console.log('required as a module'); }
See documentation for this here: https://nodejs.org/docs/latest/api/modules.html#modules_accessing_the_main_module
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With