doc: replace uses of you and other style nits

Replace uses of the pronouns `you` and `your` throughout
the docs + other minor style nits

PR-URL: https://github.com/nodejs/node/pull/12673
Reviewed-By: Vse Mozhet Byt <vsemozhetbyt@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Gibson Fahnestock <gibfahn@gmail.com>
This commit is contained in:
James M Snell 2017-04-26 10:16:12 -07:00
parent f11d4a1556
commit 71f22c842b
13 changed files with 129 additions and 125 deletions

View File

@ -37,7 +37,7 @@ involving knowledge of several components and APIs :
See [Linking to Node.js' own dependencies][] for additional information. See [Linking to Node.js' own dependencies][] for additional information.
All of the following examples are available for [download][] and may All of the following examples are available for [download][] and may
be used as a starting-point for your own Addon. be used as the starting-point for an Addon.
## Hello world ## Hello world
@ -98,7 +98,7 @@ Addon module name is `addon`.
Once the source code has been written, it must be compiled into the binary Once the source code has been written, it must be compiled into the binary
`addon.node` file. To do so, create a file called `binding.gyp` in the `addon.node` file. To do so, create a file called `binding.gyp` in the
top-level of the project describing the build configuration of your module top-level of the project describing the build configuration of the module
using a JSON-like format. This file is used by [node-gyp][] -- a tool written using a JSON-like format. This file is used by [node-gyp][] -- a tool written
specifically to compile Node.js Addons. specifically to compile Node.js Addons.

View File

@ -808,8 +808,8 @@ The `'error'` event is emitted whenever:
2. The process could not be killed, or 2. The process could not be killed, or
3. Sending a message to the child process failed. 3. Sending a message to the child process failed.
Note that the `'exit'` event may or may not fire after an error has occurred. *Note*: The `'exit'` event may or may not fire after an error has occurred.
If you are listening to both the `'exit'` and `'error'` events, it is important When listening to both the `'exit'` and `'error'` events, it is important
to guard against accidentally invoking handler functions multiple times. to guard against accidentally invoking handler functions multiple times.
See also [`child.kill()`][] and [`child.send()`][]. See also [`child.kill()`][] and [`child.send()`][].

View File

@ -5,7 +5,7 @@
Node.js comes with a variety of CLI options. These options expose built-in Node.js comes with a variety of CLI options. These options expose built-in
debugging, multiple ways to execute scripts, and other helpful runtime options. debugging, multiple ways to execute scripts, and other helpful runtime options.
To view this documentation as a manual page in your terminal, run `man node`. To view this documentation as a manual page in a terminal, run `man node`.
## Synopsis ## Synopsis

View File

@ -6,8 +6,8 @@ A single instance of Node.js runs in a single thread. To take advantage of
multi-core systems the user will sometimes want to launch a cluster of Node.js multi-core systems the user will sometimes want to launch a cluster of Node.js
processes to handle the load. processes to handle the load.
The cluster module allows you to easily create child processes that The cluster module allows easy creation of child processes that all share
all share server ports. server ports.
```js ```js
const cluster = require('cluster'); const cluster = require('cluster');
@ -88,27 +88,24 @@ Node.js process and a cluster worker differs:
idea of what the number 7 file descriptor references. idea of what the number 7 file descriptor references.
2. `server.listen(handle)` Listening on handles explicitly will cause 2. `server.listen(handle)` Listening on handles explicitly will cause
the worker to use the supplied handle, rather than talk to the master the worker to use the supplied handle, rather than talk to the master
process. If the worker already has the handle, then it's presumed process.
that you know what you are doing.
3. `server.listen(0)` Normally, this will cause servers to listen on a 3. `server.listen(0)` Normally, this will cause servers to listen on a
random port. However, in a cluster, each worker will receive the random port. However, in a cluster, each worker will receive the
same "random" port each time they do `listen(0)`. In essence, the same "random" port each time they do `listen(0)`. In essence, the
port is random the first time, but predictable thereafter. If you port is random the first time, but predictable thereafter. To listen
want to listen on a unique port, generate a port number based on the on a unique port, generate a port number based on the cluster worker ID.
cluster worker ID.
There is no routing logic in Node.js, or in your program, and no shared *Note*: Node.js does not provide routing logic. It is, therefore important to
state between the workers. Therefore, it is important to design your design an application such that it does not rely too heavily on in-memory data
program such that it does not rely too heavily on in-memory data objects objects for things like sessions and login.
for things like sessions and login.
Because workers are all separate processes, they can be killed or Because workers are all separate processes, they can be killed or
re-spawned depending on your program's needs, without affecting other re-spawned depending on a program's needs, without affecting other
workers. As long as there are some workers still alive, the server will workers. As long as there are some workers still alive, the server will
continue to accept connections. If no workers are alive, existing connections continue to accept connections. If no workers are alive, existing connections
will be dropped and new connections will be refused. Node.js does not will be dropped and new connections will be refused. Node.js does not
automatically manage the number of workers for you, however. It is your automatically manage the number of workers, however. It is the application's
responsibility to manage the worker pool for your application's needs. responsibility to manage the worker pool based on its own needs.
@ -141,7 +138,7 @@ added: v0.7.3
This event is the same as the one provided by [`child_process.fork()`][]. This event is the same as the one provided by [`child_process.fork()`][].
In a worker you can also use `process.on('error')`. Within a worker, `process.on('error')` may also be used.
### Event: 'exit' ### Event: 'exit'
<!-- YAML <!-- YAML
@ -192,8 +189,9 @@ added: v0.7.0
* `message` {Object} * `message` {Object}
* `handle` {undefined|Object} * `handle` {undefined|Object}
Similar to the `cluster.on('message')` event, but specific to this worker. In a Similar to the `cluster.on('message')` event, but specific to this worker.
worker you can also use `process.on('message')`.
Within a worker, `process.on('message)` may also be used.
See [`process` event: `'message'`][]. See [`process` event: `'message'`][].
@ -336,9 +334,9 @@ added: v6.0.0
Set by calling `.kill()` or `.disconnect()`. Until then, it is `undefined`. Set by calling `.kill()` or `.disconnect()`. Until then, it is `undefined`.
The boolean `worker.exitedAfterDisconnect` lets you distinguish between voluntary The boolean `worker.exitedAfterDisconnect` allows distinguishing between
and accidental exit, the master may choose not to respawn a worker based on voluntary and accidental exit, the master may choose not to respawn a worker
this value. based on this value.
```js ```js
cluster.on('exit', (worker, code, signal) => { cluster.on('exit', (worker, code, signal) => {
@ -369,9 +367,9 @@ cluster.workers
added: v0.11.14 added: v0.11.14
--> -->
This function returns `true` if the worker is connected to its master via its IPC This function returns `true` if the worker is connected to its master via its
channel, `false` otherwise. A worker is connected to its master after it's been IPC channel, `false` otherwise. A worker is connected to its master after it
created. It is disconnected after the `'disconnect'` event is emitted. has been created. It is disconnected after the `'disconnect'` event is emitted.
### worker.isDead() ### worker.isDead()
<!-- YAML <!-- YAML
@ -469,7 +467,7 @@ An alias to [`worker.exitedAfterDisconnect`][].
Set by calling `.kill()` or `.disconnect()`. Until then, it is `undefined`. Set by calling `.kill()` or `.disconnect()`. Until then, it is `undefined`.
The boolean `worker.suicide` lets you distinguish between voluntary The boolean `worker.suicide` is used to distinguish between voluntary
and accidental exit, the master may choose not to respawn a worker based on and accidental exit, the master may choose not to respawn a worker based on
this value. this value.
@ -540,7 +538,7 @@ added: v0.7.0
* `worker` {cluster.Worker} * `worker` {cluster.Worker}
When a new worker is forked the cluster module will emit a `'fork'` event. When a new worker is forked the cluster module will emit a `'fork'` event.
This can be used to log worker activity, and create your own timeout. This can be used to log worker activity, and create a custom timeout.
```js ```js
const timeouts = []; const timeouts = [];
@ -568,13 +566,14 @@ added: v0.7.0
* `worker` {cluster.Worker} * `worker` {cluster.Worker}
* `address` {Object} * `address` {Object}
After calling `listen()` from a worker, when the `'listening'` event is emitted on After calling `listen()` from a worker, when the `'listening'` event is emitted
the server, a `'listening'` event will also be emitted on `cluster` in the master. on the server a `'listening'` event will also be emitted on `cluster` in the
master.
The event handler is executed with two arguments, the `worker` contains the worker The event handler is executed with two arguments, the `worker` contains the
object and the `address` object contains the following connection properties: worker object and the `address` object contains the following connection
`address`, `port` and `addressType`. This is very useful if the worker is listening properties: `address`, `port` and `addressType`. This is very useful if the
on more than one address. worker is listening on more than one address.
```js ```js
cluster.on('listening', (worker, address) => { cluster.on('listening', (worker, address) => {
@ -610,8 +609,9 @@ See [child_process event: 'message'][].
Before Node.js v6.0, this event emitted only the message and the handle, Before Node.js v6.0, this event emitted only the message and the handle,
but not the worker object, contrary to what the documentation stated. but not the worker object, contrary to what the documentation stated.
If you need to support older versions and don't need the worker object, If support for older versions is required but a worker object is not
you can work around the discrepancy by checking the number of arguments: required, it is possible to work around the discrepancy by checking the
number of arguments:
```js ```js
cluster.on('message', (worker, message, handle) => { cluster.on('message', (worker, message, handle) => {
@ -713,8 +713,8 @@ added: v0.11.2
The scheduling policy, either `cluster.SCHED_RR` for round-robin or The scheduling policy, either `cluster.SCHED_RR` for round-robin or
`cluster.SCHED_NONE` to leave it to the operating system. This is a `cluster.SCHED_NONE` to leave it to the operating system. This is a
global setting and effectively frozen once you spawn the first worker global setting and effectively frozen once either the first worker is spawned,
or call `cluster.setupMaster()`, whatever comes first. or `cluster.setupMaster()` is called, whichever comes first.
`SCHED_RR` is the default on all operating systems except Windows. `SCHED_RR` is the default on all operating systems except Windows.
Windows will change to `SCHED_RR` once libuv is able to effectively Windows will change to `SCHED_RR` once libuv is able to effectively
@ -750,7 +750,7 @@ changes:
After calling `.setupMaster()` (or `.fork()`) this settings object will contain After calling `.setupMaster()` (or `.fork()`) this settings object will contain
the settings, including the default values. the settings, including the default values.
This object is not supposed to be changed or set manually, by you. This object is not intended to be changed or set manually.
## cluster.setupMaster([settings]) ## cluster.setupMaster([settings])
<!-- YAML <!-- YAML
@ -850,8 +850,7 @@ eachWorker((worker) => {
}); });
``` ```
Should you wish to reference a worker over a communication channel, using Using the worker's unique id is the easiest way to locate the worker.
the worker's unique id is the easiest way to find the worker.
```js ```js
socket.on('data', (id) => { socket.on('data', (id) => {

View File

@ -257,7 +257,7 @@ added: v0.1.104
* `label` {string} * `label` {string}
Starts a timer that can be used to compute the duration of an operation. Timers Starts a timer that can be used to compute the duration of an operation. Timers
are identified by a unique `label`. Use the same `label` when you call are identified by a unique `label`. Use the same `label` when calling
[`console.timeEnd()`][] to stop the timer and output the elapsed time in [`console.timeEnd()`][] to stop the timer and output the elapsed time in
milliseconds to `stdout`. Timer durations are accurate to the sub-millisecond. milliseconds to `stdout`. Timer durations are accurate to the sub-millisecond.

View File

@ -301,9 +301,8 @@ The only way to know for sure that the datagram has been sent is by using a
passed as the first argument to the `callback`. If a `callback` is not given, passed as the first argument to the `callback`. If a `callback` is not given,
the error is emitted as an `'error'` event on the `socket` object. the error is emitted as an `'error'` event on the `socket` object.
Offset and length are optional, but if you specify one you would need to Offset and length are optional but both *must* be set if either are used.
specify the other. Also, they are supported only when the first They are supported only when the first argument is a `Buffer` or `Uint8Array`.
argument is a `Buffer` or `Uint8Array`.
Example of sending a UDP packet to a random port on `localhost`; Example of sending a UDP packet to a random port on `localhost`;
@ -329,8 +328,10 @@ client.send([buf1, buf2], 41234, (err) => {
}); });
``` ```
Sending multiple buffers might be faster or slower depending on your Sending multiple buffers might be faster or slower depending on the
application and operating system: benchmark it. Usually it is faster. application and operating system. It is important to run benchmarks to
determine the optimal strategy on a case-by-case basis. Generally speaking,
however, sending multiple buffers is faster.
**A Note about UDP datagram size** **A Note about UDP datagram size**

View File

@ -21,14 +21,14 @@ documentation is generated using the `tools/doc/generate.js` program.
The HTML template is located at `doc/template.html`. The HTML template is located at `doc/template.html`.
If you find an error in this documentation, please [submit an issue][] If errors are found in this documentation, please [submit an issue][]
or see [the contributing guide][] for directions on how to submit a patch. or see [the contributing guide][] for directions on how to submit a patch.
## Stability Index ## Stability Index
<!--type=misc--> <!--type=misc-->
Throughout the documentation, you will see indications of a section's Throughout the documentation are indications of a section's
stability. The Node.js API is still somewhat changing, and as it stability. The Node.js API is still somewhat changing, and as it
matures, certain parts are more reliable than others. Some are so matures, certain parts are more reliable than others. Some are so
proven, and so relied upon, that they are unlikely to ever change at proven, and so relied upon, that they are unlikely to ever change at

View File

@ -27,7 +27,7 @@ exit immediately with an error code.
<!-- type=misc --> <!-- type=misc -->
Domain error handlers are not a substitute for closing down your Domain error handlers are not a substitute for closing down a
process when an error occurs. process when an error occurs.
By the very nature of how [`throw`][] works in JavaScript, there is almost By the very nature of how [`throw`][] works in JavaScript, there is almost
@ -35,8 +35,8 @@ never any way to safely "pick up where you left off", without leaking
references, or creating some other sort of undefined brittle state. references, or creating some other sort of undefined brittle state.
The safest way to respond to a thrown error is to shut down the The safest way to respond to a thrown error is to shut down the
process. Of course, in a normal web server, you might have many process. Of course, in a normal web server, there may be many
connections open, and it is not reasonable to abruptly shut those down open connections, and it is not reasonable to abruptly shut those down
because an error was triggered by someone else. because an error was triggered by someone else.
The better approach is to send an error response to the request that The better approach is to send an error response to the request that
@ -80,11 +80,11 @@ const cluster = require('cluster');
const PORT = +process.env.PORT || 1337; const PORT = +process.env.PORT || 1337;
if (cluster.isMaster) { if (cluster.isMaster) {
// In real life, you'd probably use more than just 2 workers, // A more realistic scenario would have more than 2 workers,
// and perhaps not put the master and worker in the same file. // and perhaps not put the master and worker in the same file.
// //
// You can also of course get a bit fancier about logging, and // It is also possible to get a bit fancier about logging, and
// implement whatever custom logic you need to prevent DoS // implement whatever custom logic is needed to prevent DoS
// attacks and other bad behavior. // attacks and other bad behavior.
// //
// See the options in the cluster documentation. // See the options in the cluster documentation.
@ -161,7 +161,7 @@ if (cluster.isMaster) {
} }
// This part is not important. Just an example routing thing. // This part is not important. Just an example routing thing.
// You'd put your fancy application logic here. // Put fancy application logic here.
function handleRequest(req, res) { function handleRequest(req, res) {
switch (req.url) { switch (req.url) {
case '/error': case '/error':
@ -210,8 +210,8 @@ are not implicitly added as children of the active domain. If they
were, then it would be too easy to prevent request and response objects were, then it would be too easy to prevent request and response objects
from being properly garbage collected. from being properly garbage collected.
If you *want* to nest Domain objects as children of a parent Domain, To nest Domain objects as children of a parent Domain they must be explicitly
then you must explicitly add them. added.
Implicit binding routes thrown errors and `'error'` events to the Implicit binding routes thrown errors and `'error'` events to the
Domain's `'error'` event, but does not register the EventEmitter on the Domain's `'error'` event, but does not register the EventEmitter on the

View File

@ -14,7 +14,8 @@ first argument is always reserved for an exception. If the operation was
completed successfully, then the first argument will be `null` or `undefined`. completed successfully, then the first argument will be `null` or `undefined`.
When using the synchronous form any exceptions are immediately thrown. When using the synchronous form any exceptions are immediately thrown.
You can use try/catch to handle exceptions or allow them to bubble up. Exceptions may be handled using `try`/`catch`, or they may be allowed to
bubble up.
Here is an example of the asynchronous version: Here is an example of the asynchronous version:
@ -70,9 +71,13 @@ the entire process until they complete--halting all connections.
The relative path to a filename can be used. Remember, however, that this path The relative path to a filename can be used. Remember, however, that this path
will be relative to `process.cwd()`. will be relative to `process.cwd()`.
Most fs functions let you omit the callback argument. If you do, a default While it is not recommended, most fs functions allow the callback argument to
callback is used that rethrows errors. To get a trace to the original call be omitted, in which case a default callback is used that rethrows errors. To
site, set the `NODE_DEBUG` environment variable: get a trace to the original call site, set the `NODE_DEBUG` environment
variable:
*Note*: Omitting the callback function on asynchronous fs functions is
deprecated and may result in an error being thrown in the future.
```txt ```txt
$ cat script.js $ cat script.js
@ -236,14 +241,13 @@ Stats {
``` ```
Please note that `atime`, `mtime`, `birthtime`, and `ctime` are Please note that `atime`, `mtime`, `birthtime`, and `ctime` are
instances of [`Date`][MDN-Date] object and to compare the values of instances of [`Date`][MDN-Date] object and appropriate methods should be used
these objects you should use appropriate methods. For most general to compare the values of these objects. For most general uses
uses [`getTime()`][MDN-Date-getTime] will return the number of [`getTime()`][MDN-Date-getTime] will return the number of milliseconds elapsed
milliseconds elapsed since _1 January 1970 00:00:00 UTC_ and this since _1 January 1970 00:00:00 UTC_ and this integer should be sufficient for
integer should be sufficient for any comparison, however there are any comparison, however there are additional methods which can be used for
additional methods which can be used for displaying fuzzy information. displaying fuzzy information. More details can be found in the
More details can be found in the [MDN JavaScript Reference][MDN-Date] [MDN JavaScript Reference][MDN-Date] page.
page.
### Stat Time Values ### Stat Time Values
@ -651,8 +655,8 @@ emitted. Note that `fd` should be blocking; non-blocking `fd`s should be passed
to [`net.Socket`][]. to [`net.Socket`][].
If `autoClose` is false, then the file descriptor won't be closed, even if If `autoClose` is false, then the file descriptor won't be closed, even if
there's an error. It is your responsibility to close it and make sure there's an error. It is the application's responsibility to close it and make
there's no file descriptor leak. If `autoClose` is set to true (default sure there's no file descriptor leak. If `autoClose` is set to true (default
behavior), on `error` or `end` the file descriptor will be closed behavior), on `error` or `end` the file descriptor will be closed
automatically. automatically.
@ -714,8 +718,8 @@ default mode `w`. The `defaultEncoding` can be any one of those accepted by
If `autoClose` is set to true (default behavior) on `error` or `end` If `autoClose` is set to true (default behavior) on `error` or `end`
the file descriptor will be closed automatically. If `autoClose` is false, the file descriptor will be closed automatically. If `autoClose` is false,
then the file descriptor won't be closed, even if there's an error. then the file descriptor won't be closed, even if there's an error.
It is your responsibility to close it and make sure It is the application's responsibility to close it and make sure there's no
there's no file descriptor leak. file descriptor leak.
Like [`ReadStream`][], if `fd` is specified, `WriteStream` will ignore the Like [`ReadStream`][], if `fd` is specified, `WriteStream` will ignore the
`path` argument and will use the specified file descriptor. This means that no `path` argument and will use the specified file descriptor. This means that no
@ -1327,12 +1331,12 @@ An exception occurs if the file does not exist.
* `'rs+'` - Open file for reading and writing in synchronous mode. Instructs * `'rs+'` - Open file for reading and writing in synchronous mode. Instructs
the operating system to bypass the local file system cache. the operating system to bypass the local file system cache.
This is primarily useful for opening files on NFS mounts as it allows you to This is primarily useful for opening files on NFS mounts as it allows skipping
skip the potentially stale local cache. It has a very real impact on I/O the potentially stale local cache. It has a very real impact on I/O
performance so don't use this flag unless you need it. performance so using this flag is not recommended unless it is needed.
Note that this doesn't turn `fs.open()` into a synchronous blocking call. Note that this doesn't turn `fs.open()` into a synchronous blocking call.
If that's what you want then you should be using `fs.openSync()` If synchronous operation is desired `fs.openSync()` should be used.
* `'w'` - Open file for writing. * `'w'` - Open file for writing.
The file is created (if it does not exist) or truncated (if it exists). The file is created (if it does not exist) or truncated (if it exists).
@ -1845,8 +1849,8 @@ added: v0.1.31
* `listener` {Function} * `listener` {Function}
Stop watching for changes on `filename`. If `listener` is specified, only that Stop watching for changes on `filename`. If `listener` is specified, only that
particular listener is removed. Otherwise, *all* listeners are removed and you particular listener is removed. Otherwise, *all* listeners are removed,
have effectively stopped watching `filename`. effectively stopping watching of `filename`.
Calling `fs.unwatchFile()` with a filename that is not being watched is a Calling `fs.unwatchFile()` with a filename that is not being watched is a
no-op, not an error. no-op, not an error.
@ -1968,8 +1972,8 @@ directories can be unreliable, and in some cases impossible, on network file
systems (NFS, SMB, etc), or host file systems when using virtualization software systems (NFS, SMB, etc), or host file systems when using virtualization software
such as Vagrant, Docker, etc. such as Vagrant, Docker, etc.
You can still use `fs.watchFile`, which uses stat polling, but it is slower and It is still possible to use `fs.watchFile()`, which uses stat polling, but
less reliable. this method is slower and less reliable.
#### Inodes #### Inodes
@ -2041,8 +2045,8 @@ fs.watchFile('message.text', (curr, prev) => {
These stat objects are instances of `fs.Stat`. These stat objects are instances of `fs.Stat`.
If you want to be notified when the file was modified, not just accessed, To be notified when the file was modified, not just accessed, it is necessary
you need to compare `curr.mtime` and `prev.mtime`. to compare `curr.mtime` and `prev.mtime`.
_Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will _Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will
invoke the listener once, with all the fields zeroed (or, for dates, the Unix invoke the listener once, with all the fields zeroed (or, for dates, the Unix

View File

@ -145,10 +145,10 @@ added: v0.1.27
* {Object} The global namespace object. * {Object} The global namespace object.
In browsers, the top-level scope is the global scope. That means that in In browsers, the top-level scope is the global scope. This means that
browsers if you're in the global scope `var something` will define a global within the browser `var something` will define a new global variable. In
variable. In Node.js this is different. The top-level scope is not the global Node.js this is different. The top-level scope is not the global scope;
scope; `var something` inside an Node.js module will be local to that module. `var something` inside a Node.js module will be local to that module.
## module ## module
<!-- YAML <!-- YAML

View File

@ -28,17 +28,15 @@ exports.circumference = (r) => 2 * PI * r;
``` ```
The module `circle.js` has exported the functions `area()` and The module `circle.js` has exported the functions `area()` and
`circumference()`. To add functions and objects to the root of your module, `circumference()`. Functions and objects are added to the root of a module
you can add them to the special `exports` object. by specifying additional properties on the special `exports` object.
Variables local to the module will be private, because the module is wrapped Variables local to the module will be private, because the module is wrapped
in a function by Node.js (see [module wrapper](#modules_the_module_wrapper)). in a function by Node.js (see [module wrapper](#modules_the_module_wrapper)).
In this example, the variable `PI` is private to `circle.js`. In this example, the variable `PI` is private to `circle.js`.
If you want the root of your module's export to be a function (such as a The `module.exports` property can be assigned a new value (such as a function
constructor) or if you want to export a complete object in one assignment or object).
instead of building it one property at a time, assign it to `module.exports`
instead of `exports`.
Below, `bar.js` makes use of the `square` module, which exports a constructor: Below, `bar.js` makes use of the `square` module, which exports a constructor:
@ -66,8 +64,8 @@ The module system is implemented in the `require('module')` module.
<!-- type=misc --> <!-- type=misc -->
When a file is run directly from Node.js, `require.main` is set to its When a file is run directly from Node.js, `require.main` is set to its
`module`. That means that you can determine whether a file has been run `module`. That means that it is possible to determine whether a file has been
directly by testing `require.main === module`. run directly by testing `require.main === module`.
For a file `foo.js`, this will be `true` if run via `node foo.js`, but For a file `foo.js`, this will be `true` if run via `node foo.js`, but
`false` if run by `require('./foo')`. `false` if run by `require('./foo')`.
@ -91,10 +89,10 @@ Let's say that we wanted to have the folder at
`/usr/lib/node/<some-package>/<some-version>` hold the contents of a `/usr/lib/node/<some-package>/<some-version>` hold the contents of a
specific version of a package. specific version of a package.
Packages can depend on one another. In order to install package `foo`, you Packages can depend on one another. In order to install package `foo`, it
may have to install a specific version of package `bar`. The `bar` package may be necessary to install a specific version of package `bar`. The `bar`
may itself have dependencies, and in some cases, these dependencies may even package may itself have dependencies, and in some cases, these may even collide
collide or form cycles. or form cyclic dependencies.
Since Node.js looks up the `realpath` of any modules it loads (that is, Since Node.js looks up the `realpath` of any modules it loads (that is,
resolves symlinks), and then looks for their dependencies in the `node_modules` resolves symlinks), and then looks for their dependencies in the `node_modules`
@ -203,8 +201,8 @@ executed multiple times. This is an important feature. With it,
"partially done" objects can be returned, thus allowing transitive "partially done" objects can be returned, thus allowing transitive
dependencies to be loaded even when they would cause cycles. dependencies to be loaded even when they would cause cycles.
If you want to have a module execute code multiple times, then export a To have a module execute code multiple times, export a function, and call
function, and call that function. that function.
### Module Caching Caveats ### Module Caching Caveats
@ -297,8 +295,8 @@ a done
in main, a.done=true, b.done=true in main, a.done=true, b.done=true
``` ```
If you have cyclic module dependencies in your program, make sure to Careful planning is required to allow cyclic module dependencies to work
plan accordingly. correctly within an application.
## File Modules ## File Modules
@ -391,8 +389,8 @@ this order:
This allows programs to localize their dependencies, so that they do not This allows programs to localize their dependencies, so that they do not
clash. clash.
You can require specific files or sub modules distributed with a module by It is possible to require specific files or sub modules distributed with a
including a path suffix after the module name. For instance module by including a path suffix after the module name. For instance
`require('example-module/path/to/file')` would resolve `path/to/file` `require('example-module/path/to/file')` would resolve `path/to/file`
relative to where `example-module` is located. The suffixed path follows the relative to where `example-module` is located. The suffixed path follows the
same module resolution semantics. same module resolution semantics.
@ -425,9 +423,10 @@ Additionally, Node.js will search in the following locations:
Where `$HOME` is the user's home directory, and `$PREFIX` is Node.js's Where `$HOME` is the user's home directory, and `$PREFIX` is Node.js's
configured `node_prefix`. configured `node_prefix`.
These are mostly for historic reasons. **You are highly encouraged These are mostly for historic reasons.
to place your dependencies locally in `node_modules` folders.** They
will be loaded faster, and more reliably. *Note*: It is strongly encouraged to place dependencies in the local
`node_modules` folder. These will be loaded faster, and more reliably.
## The module wrapper ## The module wrapper
@ -438,7 +437,7 @@ wrapper that looks like the following:
```js ```js
(function(exports, require, module, __filename, __dirname) { (function(exports, require, module, __filename, __dirname) {
// Your module code actually lives in here // Module code actually lives in here
}); });
``` ```
@ -488,7 +487,7 @@ The `module.exports` object is created by the Module system. Sometimes this is
not acceptable; many want their module to be an instance of some class. To do not acceptable; many want their module to be an instance of some class. To do
this, assign the desired export object to `module.exports`. Note that assigning this, assign the desired export object to `module.exports`. Note that assigning
the desired object to `exports` will simply rebind the local `exports` variable, the desired object to `exports` will simply rebind the local `exports` variable,
which is probably not what you want to do. which is probably not what is desired.
For example suppose we were making a module called `a.js` For example suppose we were making a module called `a.js`
@ -566,7 +565,7 @@ To illustrate the behavior, imagine this hypothetical implementation of
function require(/* ... */) { function require(/* ... */) {
const module = { exports: {} }; const module = { exports: {} };
((module, exports) => { ((module, exports) => {
// Your module code here. In this example, define a function. // Module code here. In this example, define a function.
function someFunc() {} function someFunc() {}
exports = someFunc; exports = someFunc;
// At this point, exports is no longer a shortcut to module.exports, and // At this point, exports is no longer a shortcut to module.exports, and
@ -628,7 +627,7 @@ added: v0.5.1
The `module.require` method provides a way to load a module as if The `module.require` method provides a way to load a module as if
`require()` was called from the original module. `require()` was called from the original module.
Note that in order to do this, you must get a reference to the `module` *Note*: In order to do this, it is necessary to get a reference to the `module`
object. Since `require()` returns the `module.exports`, and the `module` is object. Since `require()` returns the `module.exports`, and the `module` is
typically *only* available within a specific module's code, it must be typically *only* available within a specific module's code, it must be
explicitly exported in order to be used. explicitly exported in order to be used.

View File

@ -557,7 +557,7 @@ changes:
Initiate a connection on a given socket. Normally this method is not needed, Initiate a connection on a given socket. Normally this method is not needed,
the socket should be created and opened with [`net.createConnection()`][]. Use the socket should be created and opened with [`net.createConnection()`][]. Use
this only if you are implementing a custom Socket. this only when implementing a custom Socket.
For TCP connections, available `options` are: For TCP connections, available `options` are:
@ -650,8 +650,9 @@ added: v0.9.6
--> -->
The string representation of the local IP address the remote client is The string representation of the local IP address the remote client is
connecting on. For example, if you are listening on `'0.0.0.0'` and the connecting on. For example, in a server listening on `'0.0.0.0'`, if a client
client connects on `'192.168.1.1'`, the value would be `'192.168.1.1'`. connects on `'192.168.1.1'`, the value of `socket.localAddress` would be
`'192.168.1.1'`.
### socket.localPort ### socket.localPort
<!-- YAML <!-- YAML

View File

@ -499,9 +499,9 @@ by the `NODE_REPL_HISTORY` variable, as documented in the
For advanced line-editors, start Node.js with the environmental variable For advanced line-editors, start Node.js with the environmental variable
`NODE_NO_READLINE=1`. This will start the main and debugger REPL in canonical `NODE_NO_READLINE=1`. This will start the main and debugger REPL in canonical
terminal settings which will allow you to use with `rlwrap`. terminal settings, which will allow use with `rlwrap`.
For example, you could add this to your bashrc file: For example, the following can be added to a `.bashrc` file:
```text ```text
alias node="env NODE_NO_READLINE=1 rlwrap node" alias node="env NODE_NO_READLINE=1 rlwrap node"