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?
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.
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.
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
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