Documenting `require.main`, fixing #997
authorTrevor Burnham <trevorburnham@gmail.com>
Sun, 1 May 2011 18:03:08 +0000 (14:03 -0400)
committerRyan Dahl <ry@tinyclouds.org>
Mon, 9 May 2011 17:29:09 +0000 (10:29 -0700)
doc/api/modules.markdown

index 07ff31f..89490eb 100644 (file)
@@ -305,6 +305,21 @@ the same process.  As the application stack grows, we tend to assemble
 functionality, and it is a problem with those parts interact in ways
 that are difficult to predict.
 
+### Accessing the main module
+
+When a file is run directly from Node, `require.main` is set to its
+`module`. That means that you can determine whether a file has been run
+directly by testing
+
+    require.main === module
+
+For a file `foo.js`, this will be `true` if run via `node foo.js`, but
+`false` if run by `require('./foo')`.
+
+Because `module` provides a `filename` property (normally equivalent to
+`__filename`), the entry point of the current application can be obtained
+by checking `require.main.filename`.
+
 ## Addenda: Package Manager Tips
 
 The semantics of Node's `require()` function were designed to be general