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 119 times
1
iconoclast
- 19,365
- 11
- 98
- 131
jiyinyiyong
- 4,350
- 7
- 43
- 84
-
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
- 37,450
- 36
- 118
- 151