Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if called through require or directly by command line

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?

like image 927
700 Software Avatar asked Jun 18 '11 18:06

700 Software


People also ask

What is require main === module?

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 .

Do you need to use require () to get the global object?

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 node CLI?

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.

What is require () in JavaScript?

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.


1 Answers

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

like image 191
nicolaskruchten Avatar answered Sep 20 '22 19:09

nicolaskruchten