If your code detects that it is called by require
, you may want it to branch accordingly, doing or not doing certain things in each case. How do I do this?
Asked
Active
Viewed 123 times
1

iconoclast
- 21,213
- 15
- 102
- 138

jiyinyiyong
- 4,586
- 7
- 45
- 88
-
Not entirely sure why you would want to do this. If you could explain what you are trying to do, that may help. – Nick Sep 05 '12 at 20:44
-
When I am writing some code which will be used in another script, I usually write some tests in the same file. But After finished, that code should be removed or commented. I don't like that. So I want to know if there's friendly way to hide it, with kepping it in the same file. – jiyinyiyong Sep 06 '12 at 00:48
-
Exact duplicate of http://stackoverflow.com/questions/4981891/node-js-equivalent-of-pythons-if-name-main. – JohnnyHK Sep 07 '12 at 00:37
1 Answers
2
Sure, just check if module.parent
is not null
or undefined
. If it is set with an object, then your module is being called with require
.

JP Richardson
- 38,609
- 36
- 119
- 151