RienNeVaPlu͢s
RienNeVaPlu͢s

Reputation: 7632

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

Upvotes: 0

Views: 197

Answers (1)

mscdex
mscdex

Reputation: 106696

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.

Upvotes: 2

Related Questions