I’d like to check if my module is being included or run directly. How can I do this in node.js?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The nodejs docs describe another way to do this which may be the preferred method:
To take advantage of this, check if this module is the main module and, if so, call your main code:
EDIT: If you use this code in a browser, you will get a "Reference error" since "require" is not defined. To prevent this, use: