Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I know, in node.js, if my script is being run directly or being loaded by another script?

Tags:

node.js

module

I'm just getting started with node.js and I have some experience with Python. In Python I could check whether the __name__ variable was set to "__main__", and if it was I'd know that my script was being run directly. In that case I could run test code or make use of the module directly in other ways.

Is there anything similar in node.js?

like image 916
Hubro Avatar asked Jan 14 '12 18:01

Hubro


People also ask

Does node JS have the same syntax as JavaScript?

No. The Syntax is exactly the same. There are differences in the apis however. The standard browser dom is not available in node but it has additional apis found at nodejs.org.

Do I have to install Node JS to run JavaScript?

You can Run your JavaScript File from your Terminal only if you have installed NodeJs runtime. If you have Installed it then Simply open the terminal and type “node FileName. js”. If you don't have NodeJs runtime environment then go to NodeJs Runtime Environment Download and Download it.


1 Answers

You can use module.parent to determine if the current script is loaded by another script.

e.g.

a.js:

if (!module.parent) {     console.log("I'm parent"); } else {     console.log("I'm child"); } 

b.js:

require('./a') 

run node a.js will output:

I'm parent 

run node b.js will output:

I'm child 
like image 112
qiao Avatar answered Sep 20 '22 04:09

qiao