简体   繁体   中英

How to detect if a script is executed directly from the node console

Is it possible to determine whether the current script is executed from using the node.js console :

$ node
> require('./script');

or from running the classic way of using a file like:

node script.js

You could check module.parent !== null . If that is true, then the file is being require() d from some other script. If that statement is false, then it is the script loaded initially from the command line.

If you want to know specifically if the parent was the repl, you could check module.parent && module.parent.id === 'repl' .

module.parent is documented here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM