Browse Source

doc: add links and backticks around names

* add backticks around names
* add single quotes around event names
* add parenthesis after function names
* add internal links between different sections
* add external links to MDN for some JavaScript references
* sort the link definitions alphabetically

PR-URL: https://github.com/nodejs/node/pull/4054
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Roman Reiss <me@silverwind.io>
process-exit-stdio-flushing
jpersson 9 years ago
committed by James M Snell
parent
commit
14b3aab7d2
  1. 21
      doc/api/assert.markdown
  2. 25
      doc/api/buffer.markdown
  3. 68
      doc/api/child_process.markdown
  4. 41
      doc/api/cluster.markdown
  5. 27
      doc/api/console.markdown
  6. 59
      doc/api/crypto.markdown
  7. 56
      doc/api/dgram.markdown
  8. 34
      doc/api/dns.markdown
  9. 52
      doc/api/domain.markdown
  10. 82
      doc/api/errors.markdown
  11. 117
      doc/api/fs.markdown
  12. 16
      doc/api/globals.markdown
  13. 200
      doc/api/http.markdown
  14. 66
      doc/api/https.markdown
  15. 5
      doc/api/modules.markdown
  16. 138
      doc/api/net.markdown
  17. 80
      doc/api/process.markdown
  18. 34
      doc/api/readline.markdown
  19. 16
      doc/api/repl.markdown
  20. 138
      doc/api/stream.markdown
  21. 2
      doc/api/string_decoder.markdown
  22. 2
      doc/api/synopsis.markdown
  23. 7
      doc/api/timers.markdown
  24. 28
      doc/api/tls.markdown
  25. 4
      doc/api/tty.markdown
  26. 6
      doc/api/util.markdown
  27. 7
      doc/api/vm.markdown

21
doc/api/assert.markdown

@ -19,7 +19,7 @@ comparison operator ( `==` ).
This only considers enumerable properties. It does not test object prototypes, This only considers enumerable properties. It does not test object prototypes,
attached symbols, or non-enumerable properties. This can lead to some attached symbols, or non-enumerable properties. This can lead to some
potentially surprising results. For example, this does not throw an potentially surprising results. For example, this does not throw an
`AssertionError` because the properties on the `Error` object are `AssertionError` because the properties on the [`Error`][] object are
non-enumerable: non-enumerable:
// WARNING: This does not throw an AssertionError! // WARNING: This does not throw an AssertionError!
@ -32,11 +32,11 @@ operator ( `===` ).
## assert.doesNotThrow(block[, error][, message]) ## assert.doesNotThrow(block[, error][, message])
Expects `block` not to throw an error. See [assert.throws()][] for more details. Expects `block` not to throw an error. See [`assert.throws()`][] for more details.
If `block` throws an error and if it is of a different type from `error`, the If `block` throws an error and if it is of a different type from `error`, the
thrown error will get propagated back to the caller. The following call will thrown error will get propagated back to the caller. The following call will
throw the `TypeError`, since we're not matching the error types in the throw the [`TypeError`][], since we're not matching the error types in the
assertion. assertion.
assert.doesNotThrow( assert.doesNotThrow(
@ -72,11 +72,11 @@ argument in callbacks.
## assert.notDeepEqual(actual, expected[, message]) ## assert.notDeepEqual(actual, expected[, message])
Tests for any deep inequality. Opposite of `assert.deepEqual`. Tests for any deep inequality. Opposite of [`assert.deepEqual`][].
## assert.notDeepStrictEqual(actual, expected[, message]) ## assert.notDeepStrictEqual(actual, expected[, message])
Tests for deep inequality. Opposite of `assert.deepStrictEqual`. Tests for deep inequality. Opposite of [`assert.deepStrictEqual`][].
## assert.notEqual(actual, expected[, message]) ## assert.notEqual(actual, expected[, message])
@ -94,7 +94,7 @@ Tests strict equality as determined by the strict equality operator ( `===` ).
## assert.throws(block[, error][, message]) ## assert.throws(block[, error][, message])
Expects `block` to throw an error. `error` can be a constructor, `RegExp`, or Expects `block` to throw an error. `error` can be a constructor, [`RegExp`][], or
validation function. validation function.
Validate instanceof using constructor: Validate instanceof using constructor:
@ -106,7 +106,7 @@ Validate instanceof using constructor:
Error Error
); );
Validate error message using RegExp: Validate error message using [`RegExp`][]:
assert.throws( assert.throws(
function() { function() {
@ -129,4 +129,9 @@ Custom error validation:
"unexpected error" "unexpected error"
); );
[assert.throws()]: #assert_assert_throws_block_error_message [`assert.deepEqual`]: #assert_assert_deepequal_actual_expected_message
[`assert.deepStrictEqual`]: #assert_assert_deepstrictequal_actual_expected_message
[`assert.throws()`]: #assert_assert_throws_block_error_message
[`Error`]: errors.html#errors_class_error
[`RegExp`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
[`TypeError`]: errors.html#errors_class_typeerror

25
doc/api/buffer.markdown

@ -50,7 +50,7 @@ instead of cloning it.
While more efficient, it introduces subtle incompatibilities with the typed While more efficient, it introduces subtle incompatibilities with the typed
arrays specification. `ArrayBuffer#slice()` makes a copy of the slice while arrays specification. `ArrayBuffer#slice()` makes a copy of the slice while
`Buffer#slice()` creates a view. [`Buffer#slice()`][] creates a view.
## Class: Buffer ## Class: Buffer
@ -76,11 +76,11 @@ Copies the passed `buffer` data onto a new `Buffer` instance.
Allocates a new buffer of `size` bytes. `size` must be less than Allocates a new buffer of `size` bytes. `size` must be less than
1,073,741,824 bytes (1 GB) on 32 bits architectures or 1,073,741,824 bytes (1 GB) on 32 bits architectures or
2,147,483,648 bytes (2 GB) on 64 bits architectures, 2,147,483,648 bytes (2 GB) on 64 bits architectures,
otherwise a `RangeError` is thrown. otherwise a [`RangeError`][] is thrown.
Unlike `ArrayBuffers`, the underlying memory for buffers is not initialized. So Unlike `ArrayBuffers`, the underlying memory for buffers is not initialized. So
the contents of a newly created `Buffer` are unknown and could contain the contents of a newly created `Buffer` are unknown and could contain
sensitive data. Use `buf.fill(0)` to initialize a buffer to zeroes. sensitive data. Use [`buf.fill(0)`][] to initialize a buffer to zeroes.
### new Buffer(str[, encoding]) ### new Buffer(str[, encoding])
@ -97,7 +97,7 @@ Allocates a new buffer containing the given `str`.
* Return: Number * Return: Number
Gives the actual byte length of a string. `encoding` defaults to `'utf8'`. Gives the actual byte length of a string. `encoding` defaults to `'utf8'`.
This is not the same as `String.prototype.length` since that returns the This is not the same as [`String.prototype.length`][] since that returns the
number of *characters* in a string. number of *characters* in a string.
Example: Example:
@ -286,9 +286,9 @@ buffer.
* `byteOffset` Number, Optional, Default: 0 * `byteOffset` Number, Optional, Default: 0
* Return: Number * Return: Number
Operates similar to [Array#indexOf()][]. Accepts a String, Buffer or Number. Operates similar to [`Array#indexOf()`][]. Accepts a String, Buffer or Number.
Strings are interpreted as UTF8. Buffers will use the entire buffer. So in order Strings are interpreted as UTF8. Buffers will use the entire buffer. So in order
to compare a partial Buffer use `Buffer#slice()`. Numbers can range from 0 to to compare a partial Buffer use [`Buffer#slice()`][]. Numbers can range from 0 to
255. 255.
### buf.length ### buf.length
@ -311,7 +311,7 @@ buffer object. It does not change when the contents of the buffer are changed.
While the `length` property is not immutable, changing the value of `length` While the `length` property is not immutable, changing the value of `length`
can result in undefined and inconsistent behavior. Applications that wish to can result in undefined and inconsistent behavior. Applications that wish to
modify the length of a buffer should therefore treat `length` as read-only and modify the length of a buffer should therefore treat `length` as read-only and
use `buf.slice` to create a new buffer. use [`buf.slice`][] to create a new buffer.
buf = new Buffer(10); buf = new Buffer(10);
buf.write("abcdefghj", 0, "ascii"); buf.write("abcdefghj", 0, "ascii");
@ -882,7 +882,7 @@ to `false`.
* Number, Default: 50 * Number, Default: 50
How many bytes will be returned when `buffer.inspect()` is called. This can How many bytes will be returned when `buffer.inspect()` is called. This can
be overridden by user modules. See [util.inspect()][] for more details on be overridden by user modules. See [`util.inspect()`][] for more details on
`buffer.inspect()` behavior. `buffer.inspect()` behavior.
Note that this is a property on the buffer module returned by Note that this is a property on the buffer module returned by
@ -932,6 +932,11 @@ un-pooled Buffer instance using SlowBuffer and copy out the relevant bits.
Though this should be used sparingly and only be a last resort *after* a developer Though this should be used sparingly and only be a last resort *after* a developer
has actively observed undue memory retention in their applications. has actively observed undue memory retention in their applications.
[`Array#indexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
[`buf.fill(0)`]: #buffer_buf_fill_value_offset_end
[`buf.slice`]: #buffer_buf_slice_start_end
[`buf1.compare(buf2)`]: #buffer_buf_compare_otherbuffer [`buf1.compare(buf2)`]: #buffer_buf_compare_otherbuffer
[Array#indexOf()]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf [`Buffer#slice()`]: #buffer_buf_slice_start_end
[util.inspect()]: util.html#util_util_inspect_object_options [`RangeError`]: errors.html#errors_class_rangeerror
[`String.prototype.length`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length
[`util.inspect()`]: util.html#util_util_inspect_object_options

68
doc/api/child_process.markdown

@ -19,7 +19,7 @@ convenient.
## Class: ChildProcess ## Class: ChildProcess
`ChildProcess` is an [EventEmitter][]. `ChildProcess` is an [`EventEmitter`][].
Child processes always have three streams associated with them. `child.stdin`, Child processes always have three streams associated with them. `child.stdin`,
`child.stdout`, and `child.stderr`. These may be shared with the stdio `child.stdout`, and `child.stderr`. These may be shared with the stdio
@ -27,7 +27,7 @@ streams of the parent process, or they may be separate stream objects
which can be piped to and from. which can be piped to and from.
The ChildProcess class is not intended to be used directly. Use the The ChildProcess class is not intended to be used directly. Use the
`spawn()`, `exec()`, `execFile()`, or `fork()` methods to create a Child [`spawn()`][], [`exec()`][], [`execFile()`][], or [`fork()`][] methods to create a Child
Process instance. Process instance.
### Event: 'close' ### Event: 'close'
@ -37,7 +37,7 @@ Process instance.
was killed by the parent. was killed by the parent.
This event is emitted when the stdio streams of a child process have all This event is emitted when the stdio streams of a child process have all
terminated. This is distinct from 'exit', since multiple processes terminated. This is distinct from `'exit'`, since multiple processes
might share the same stdio streams. might share the same stdio streams.
### Event: 'disconnect' ### Event: 'disconnect'
@ -56,7 +56,7 @@ Emitted when:
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 for whatever reason. 3. Sending a message to the child process failed for whatever reason.
Note that the `exit`-event may or may not fire after an error has occurred. If Note that the `'exit'` event may or may not fire after an error has occurred. If
you are listening on both events to fire a function, remember to guard against you are listening on both events to fire a function, remember to guard against
calling your function twice. calling your function twice.
@ -75,8 +75,8 @@ of the signal, otherwise `null`.
Note that the child process stdio streams might still be open. Note that the child process stdio streams might still be open.
Also, note that Node.js establishes signal handlers for `'SIGINT'` and Also, note that Node.js establishes signal handlers for `SIGINT` and
`'SIGTERM`', so it will not terminate due to receipt of those signals, `SIGTERM`, so it will not terminate due to receipt of those signals,
it will exit. it will exit.
See `waitpid(2)`. See `waitpid(2)`.
@ -84,11 +84,11 @@ See `waitpid(2)`.
### Event: 'message' ### Event: 'message'
* `message` {Object} a parsed JSON object or primitive value. * `message` {Object} a parsed JSON object or primitive value.
* `sendHandle` {Handle object} a [net.Socket][] or [net.Server][] object, or * `sendHandle` {Handle object} a [`net.Socket`][] or [`net.Server`][] object, or
undefined. undefined.
Messages sent by `.send(message, [sendHandle])` are obtained using the Messages sent by `.send(message, [sendHandle])` are obtained using the
`message` event. `'message'` event.
### child.connected ### child.connected
@ -103,11 +103,11 @@ gracefully once there are no other connections keeping it alive. After calling
this method the `.connected` flag will be set to `false` in both the parent and this method the `.connected` flag will be set to `false` in both the parent and
child, and it is no longer possible to send messages. child, and it is no longer possible to send messages.
The 'disconnect' event will be emitted when there are no messages in the process The `'disconnect'` event will be emitted when there are no messages in the process
of being received, most likely immediately. of being received, most likely immediately.
Note that you can also call `process.disconnect()` in the child process when the Note that you can also call `process.disconnect()` in the child process when the
child process has any open IPC channels with the parent (i.e `fork()`). child process has any open IPC channels with the parent (i.e [`fork()`][]).
### child.kill([signal]) ### child.kill([signal])
@ -188,17 +188,17 @@ will emit objects each time it receives a message on its channel.
There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages
containing a `NODE_` prefix in its `cmd` property will not be emitted in containing a `NODE_` prefix in its `cmd` property will not be emitted in
the `message` event, since they are internal messages used by Node.js core. the `'message'` event, since they are internal messages used by Node.js core.
Messages containing the prefix are emitted in the `internalMessage` event. Messages containing the prefix are emitted in the `'internalMessage'` event.
Avoid using this feature; it is subject to change without notice. Avoid using this feature; it is subject to change without notice.
The `sendHandle` option to `child.send()` is for sending a TCP server or The `sendHandle` option to `child.send()` is for sending a TCP server or
socket object to another process. The child will receive the object as its socket object to another process. The child will receive the object as its
second argument to the `message` event. second argument to the `'message'` event.
The `callback` option is a function that is invoked after the message is The `callback` option is a function that is invoked after the message is
sent but before the target may have received it. It is called with a single sent but before the target may have received it. It is called with a single
argument: `null` on success, or an `Error` object on failure. argument: `null` on success, or an [`Error`][] object on failure.
`child.send()` emits an `'error'` event if no callback was given and the message `child.send()` emits an `'error'` event if no callback was given and the message
cannot be sent, for example because the child process has already exited. cannot be sent, for example because the child process has already exited.
@ -237,7 +237,7 @@ Note that the server is now shared between the parent and child, this means
that some connections will be handled by the parent and some by the child. that some connections will be handled by the parent and some by the child.
For `dgram` servers the workflow is exactly the same. Here you listen on For `dgram` servers the workflow is exactly the same. Here you listen on
a `message` event instead of `connection` and use `server.bind` instead of a `'message'` event instead of `'connection'` and use `server.bind` instead of
`server.listen`. (Currently only supported on UNIX platforms.) `server.listen`. (Currently only supported on UNIX platforms.)
#### Example: sending socket object #### Example: sending socket object
@ -308,7 +308,7 @@ to the same object, or null.
* {Array} * {Array}
A sparse array of pipes to the child process, corresponding with positions in A sparse array of pipes to the child process, corresponding with positions in
the [stdio][] option to [spawn][] that have been set to `'pipe'`. the [`stdio`][] option to [`spawn()`][] that have been set to `'pipe'`.
Note that streams 0-2 are also available as ChildProcess.stdin, Note that streams 0-2 are also available as ChildProcess.stdin,
ChildProcess.stdout, and ChildProcess.stderr, respectively. ChildProcess.stdout, and ChildProcess.stderr, respectively.
@ -392,7 +392,7 @@ Runs a command in a shell and buffers the output.
}); });
The callback gets the arguments `(error, stdout, stderr)`. On success, `error` The callback gets the arguments `(error, stdout, stderr)`. On success, `error`
will be `null`. On error, `error` will be an instance of `Error` and `error.code` will be `null`. On error, `error` will be an instance of [`Error`][] and `error.code`
will be the exit code of the child process, and `error.signal` will be set to the will be the exit code of the child process, and `error.signal` will be set to the
signal that terminated the process. signal that terminated the process.
@ -452,7 +452,7 @@ leaner than [`child_process.exec()`][]. It has the same options.
(Default: `process.execArgv`) (Default: `process.execArgv`)
* `silent` {Boolean} If true, stdin, stdout, and stderr of the child will be * `silent` {Boolean} If true, stdin, stdout, and stderr of the child will be
piped to the parent, otherwise they will be inherited from the parent, see piped to the parent, otherwise they will be inherited from the parent, see
the "pipe" and "inherit" options for `spawn()`'s `stdio` for more details the `'pipe'` and `'inherit'` options for [`spawn()`][]'s [`stdio`][] for more details
(default is false) (default is false)
* `uid` {Number} Sets the user identity of the process. (See setuid(2).) * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
* `gid` {Number} Sets the group identity of the process. (See setgid(2).) * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
@ -473,7 +473,7 @@ done with care and by default will talk over the fd represented an
environmental variable `NODE_CHANNEL_FD` on the child process. The input and environmental variable `NODE_CHANNEL_FD` on the child process. The input and
output on this fd is expected to be line delimited JSON objects. output on this fd is expected to be line delimited JSON objects.
*Note: Unlike the `fork()` POSIX system call, `child_process.fork()` does not clone the *Note: Unlike the `fork()` POSIX system call, [`child_process.fork()`][] does not clone the
current process.* current process.*
### child_process.spawn(command[, args][, options]) ### child_process.spawn(command[, args][, options])
@ -614,7 +614,7 @@ As a shorthand, the `stdio` argument may be one of the following strings:
* `'ignore'` - `['ignore', 'ignore', 'ignore']` * `'ignore'` - `['ignore', 'ignore', 'ignore']`
* `'inherit'` - `[process.stdin, process.stdout, process.stderr]` or `[0,1,2]` * `'inherit'` - `[process.stdin, process.stdout, process.stderr]` or `[0,1,2]`
Otherwise, the 'stdio' option to `child_process.spawn()` is an array where each Otherwise, the `'stdio'` option to [`child_process.spawn()`][] is an array where each
index corresponds to a fd in the child. The value is one of the following: index corresponds to a fd in the child. The value is one of the following:
1. `'pipe'` - Create a pipe between the child process and the parent process. 1. `'pipe'` - Create a pipe between the child process and the parent process.
@ -698,7 +698,7 @@ the `SIGTERM` signal and doesn't exit, your process will wait until the child
process has exited. process has exited.
If the process times out, or has a non-zero exit code, this method ***will*** If the process times out, or has a non-zero exit code, this method ***will***
throw. The `Error` object will contain the entire result from throw. The [`Error`][] object will contain the entire result from
[`child_process.spawnSync()`][] [`child_process.spawnSync()`][]
### child_process.execSync(command[, options]) ### child_process.execSync(command[, options])
@ -732,7 +732,7 @@ the `SIGTERM` signal and doesn't exit, your process will wait until the child
process has exited. process has exited.
If the process times out, or has a non-zero exit code, this method ***will*** If the process times out, or has a non-zero exit code, this method ***will***
throw. The `Error` object will contain the entire result from throw. The [`Error`][] object will contain the entire result from
[`child_process.spawnSync()`][] [`child_process.spawnSync()`][]
### child_process.spawnSync(command[, args][, options]) ### child_process.spawnSync(command[, args][, options])
@ -767,16 +767,20 @@ until the process has completely exited. That is to say, if the process handles
the `SIGTERM` signal and doesn't exit, your process will wait until the child the `SIGTERM` signal and doesn't exit, your process will wait until the child
process has exited. process has exited.
[below]: #child_process_asynchronous_process_creation
[synchronous counterparts]: #child_process_synchronous_process_creation
[EventEmitter]: events.html#events_class_events_eventemitter
[`ChildProcess#kill()`]: #child_process_child_kill_signal
[`ChildProcess#send()`]: #child_process_child_send_message_sendhandle_callback
[net.Server]: net.html#net_class_net_server
[net.Socket]: net.html#net_class_net_socket
[`child_process.fork()`]: #child_process_child_process_fork_modulepath_args_options
[stdio]: #child_process_options_stdio
[spawn]: #child_process_child_process_spawn_command_args_options
[`child_process.exec()`]: #child_process_child_process_exec_command_options_callback [`child_process.exec()`]: #child_process_child_process_exec_command_options_callback
[`child_process.fork()`]: #child_process_child_process_fork_modulepath_args_options
[`child_process.spawn()`]: #child_process_child_process_spawn_command_args_options [`child_process.spawn()`]: #child_process_child_process_spawn_command_args_options
[`child_process.spawnSync()`]: #child_process_child_process_spawnsync_command_args_options [`child_process.spawnSync()`]: #child_process_child_process_spawnsync_command_args_options
[`ChildProcess#kill()`]: #child_process_child_kill_signal
[`ChildProcess#send()`]: #child_process_child_send_message_sendhandle_callback
[`Error`]: errors.html#errors_class_error
[`EventEmitter`]: events.html#events_class_events_eventemitter
[`exec()`]: #child_process_child_process_exec_command_options_callback
[`execFile()`]: #child_process_child_process_execfile_file_args_options_callback
[`fork()`]: #child_process_child_process_fork_modulepath_args_options
[`net.Server`]: net.html#net_class_net_server
[`net.Socket`]: net.html#net_class_net_socket
[`spawn()`]: #child_process_child_process_spawn_command_args_options
[`stdio`]: #child_process_options_stdio
[below]: #child_process_asynchronous_process_creation
[synchronous counterparts]: #child_process_synchronous_process_creation

41
doc/api/cluster.markdown

@ -46,7 +46,7 @@ server in a worker.
<!--type=misc--> <!--type=misc-->
The worker processes are spawned using the `child_process.fork` method, The worker processes are spawned using the [`child_process.fork`][] method,
so that they can communicate with the parent via IPC and pass server so that they can communicate with the parent via IPC and pass server
handles back and forth. handles back and forth.
@ -119,7 +119,7 @@ Similar to the `cluster.on('disconnect')` event, but specific to this worker.
### Event: 'error' ### Event: 'error'
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')`. In a worker you can also use `process.on('error')`.
@ -160,7 +160,7 @@ It is not emitted in the worker.
Similar to the `cluster.on('message')` event, but specific to this worker. Similar to the `cluster.on('message')` event, but specific to this worker.
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('message')`. In a worker you can also use `process.on('message')`.
@ -219,7 +219,7 @@ It is not emitted in the worker.
### worker.disconnect() ### worker.disconnect()
In a worker, this function will close all servers, wait for the 'close' event on In a worker, this function will close all servers, wait for the `'close'` event on
those servers, and then disconnect the IPC channel. those servers, and then disconnect the IPC channel.
In the master, an internal message is sent to the worker causing it to call In the master, an internal message is sent to the worker causing it to call
@ -238,12 +238,12 @@ automatically closed by workers, and disconnect does not wait for them to close
before exiting. before exiting.
Note that in a worker, `process.disconnect` exists, but it is not this function, Note that in a worker, `process.disconnect` exists, but it is not this function,
it is [disconnect][]. it is [`disconnect`][].
Because long living server connections may block workers from disconnecting, it Because long living server connections may block workers from disconnecting, it
may be useful to send a message, so application specific actions may be taken to may be useful to send a message, so application specific actions may be taken to
close them. It also may be useful to implement a timeout, killing a worker if close them. It also may be useful to implement a timeout, killing a worker if
the `disconnect` event has not been emitted after some time. the `'disconnect'` event has not been emitted after some time.
if (cluster.isMaster) { if (cluster.isMaster) {
var worker = cluster.fork(); var worker = cluster.fork();
@ -290,7 +290,7 @@ cluster.workers
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 IPC
channel, `false` otherwise. A worker is connected to its master after it's been channel, `false` otherwise. A worker is connected to its master after it's been
created. It is disconnected after the `disconnect` event is emitted. created. It is disconnected after the `'disconnect'` event is emitted.
### worker.isDead() ### worker.isDead()
@ -311,13 +311,13 @@ Causes `.suicide` to be set.
This method is aliased as `worker.destroy()` for backwards compatibility. This method is aliased as `worker.destroy()` for backwards compatibility.
Note that in a worker, `process.kill()` exists, but it is not this function, Note that in a worker, `process.kill()` exists, but it is not this function,
it is [kill][]. it is [`kill`][].
### worker.process ### worker.process
* {ChildProcess object} * {ChildProcess object}
All workers are created using `child_process.fork()`, the returned object All workers are created using [`child_process.fork()`][], the returned object
from this function is stored as `.process`. In a worker, the global `process` from this function is stored as `.process`. In a worker, the global `process`
is stored. is stored.
@ -337,7 +337,7 @@ disconnection.
Send a message to a worker or master, optionally with a handle. Send a message to a worker or master, optionally with a handle.
In the master this sends a message to a specific worker. It is identical to In the master this sends a message to a specific worker. It is identical to
[ChildProcess.send()][]. [`ChildProcess.send()`][].
In a worker this sends a message to the master. It is identical to In a worker this sends a message to the master. It is identical to
`process.send()`. `process.send()`.
@ -380,7 +380,7 @@ Emitted after the worker IPC channel has disconnected. This can occur when a
worker exits gracefully, is killed, or is disconnected manually (such as with worker exits gracefully, is killed, or is disconnected manually (such as with
worker.disconnect()). worker.disconnect()).
There may be a delay between the `disconnect` and `exit` events. These events There may be a delay between the `'disconnect'` and `'exit'` events. These events
can be used to detect if the process is stuck in a cleanup or if there are can be used to detect if the process is stuck in a cleanup or if there are
long-living connections. long-living connections.
@ -395,7 +395,7 @@ long-living connections.
* `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused * `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused
the process to be killed. the process to be killed.
When any of the workers die the cluster module will emit the 'exit' event. When any of the workers die the cluster module will emit the `'exit'` event.
This can be used to restart the worker by calling `.fork()` again. This can be used to restart the worker by calling `.fork()` again.
@ -411,7 +411,7 @@ See [child_process event: 'exit'][].
* `worker` {Worker object} * `worker` {Worker object}
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 your own timeout.
var timeouts = []; var timeouts = [];
@ -435,8 +435,8 @@ This can be used to log worker activity, and create your own timeout.
* `worker` {Worker object} * `worker` {Worker object}
* `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 on
the server, a listening event will also be emitted on `cluster` in the master. 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 worker
object and the `address` object contains the following connection properties: object and the `address` object contains the following connection properties:
@ -469,7 +469,7 @@ See [child_process event: 'message'][].
After forking a new worker, the worker should respond with an online message. After forking a new worker, the worker should respond with an online message.
When the master receives an online message it will emit this event. When the master receives an online message it will emit this event.
The difference between 'fork' and 'online' is that fork is emitted when the The difference between `'fork'` and `'online'` is that fork is emitted when the
master forks a worker, and 'online' is emitted when the worker is running. master forks a worker, and 'online' is emitted when the worker is running.
cluster.on('online', function(worker) { cluster.on('online', function(worker) {
@ -644,10 +644,11 @@ the worker's unique id is the easiest way to find the worker.
var worker = cluster.workers[id]; var worker = cluster.workers[id];
}); });
[server.close()]: net.html#net_event_close [`child_process.fork()`]: child_process.html#child_process_child_process_fork_modulepath_args_options
[disconnect]: child_process.html#child_process_child_disconnect [`ChildProcess.send()`]: child_process.html#child_process_child_send_message_sendhandle_callback
[kill]: process.html#process_process_kill_pid_signal [`disconnect`]: child_process.html#child_process_child_disconnect
[`kill`]: process.html#process_process_kill_pid_signal
[`server.close()`]: net.html#net_event_close
[Child Process module]: child_process.html#child_process_child_process_fork_modulepath_args_options [Child Process module]: child_process.html#child_process_child_process_fork_modulepath_args_options
[ChildProcess.send()]: child_process.html#child_process_child_send_message_sendhandle_callback
[child_process event: 'exit']: child_process.html#child_process_event_exit [child_process event: 'exit']: child_process.html#child_process_event_exit
[child_process event: 'message']: child_process.html#child_process_event_message [child_process event: 'message']: child_process.html#child_process_event_message

27
doc/api/console.markdown

@ -66,12 +66,12 @@ should worry about unless you log huge amounts of data.
### console.assert(value[, message][, ...]) ### console.assert(value[, message][, ...])
Similar to [assert.ok()][], but the error message is formatted as Similar to [`assert.ok()`][], but the error message is formatted as
`util.format(message...)`. `util.format(message...)`.
### console.dir(obj[, options]) ### console.dir(obj[, options])
Uses `util.inspect` on `obj` and prints resulting string to stdout. This function Uses [`util.inspect()`][] on `obj` and prints resulting string to stdout. This function
bypasses any custom `inspect()` function on `obj`. An optional *options* object bypasses any custom `inspect()` function on `obj`. An optional *options* object
may be passed that alters certain aspects of the formatted string: may be passed that alters certain aspects of the formatted string:
@ -83,15 +83,15 @@ object. This is useful for inspecting large complicated objects. Defaults to
`2`. To make it recurse indefinitely pass `null`. `2`. To make it recurse indefinitely pass `null`.
- `colors` - if `true`, then the output will be styled with ANSI color codes. - `colors` - if `true`, then the output will be styled with ANSI color codes.
Defaults to `false`. Colors are customizable, see [customizing util.inspect colors][]. Defaults to `false`. Colors are customizable, see [customizing `util.inspect()` colors][].
### console.error([data][, ...]) ### console.error([data][, ...])
Same as `console.log` but prints to stderr. Same as [`console.log()`][] but prints to stderr.
### console.info([data][, ...]) ### console.info([data][, ...])
Same as `console.log`. Same as [`console.log()`][].
### console.log([data][, ...]) ### console.log([data][, ...])
@ -102,8 +102,8 @@ Prints to stdout with newline. This function can take multiple arguments in a
console.log('count: %d', count); console.log('count: %d', count);
// prints 'count: 5' // prints 'count: 5'
If formatting elements are not found in the first string then `util.inspect` If formatting elements are not found in the first string then [`util.inspect()`][]
is used on each argument. See [util.format()][] for more information. is used on each argument. See [`util.format()`][] for more information.
### console.time(label) ### console.time(label)
@ -134,10 +134,13 @@ to the current position.
### console.warn([data][, ...]) ### console.warn([data][, ...])
Same as `console.error`. Same as [`console.error()`][].
[assert.ok()]: assert.html#assert_assert_value_message_assert_ok_value_message [`assert.ok()`]: assert.html#assert_assert_value_message_assert_ok_value_message
[customizing util.inspect colors]: util.html#util_customizing_util_inspect_colors [`console.error()`]: #console_console_error_data
[util.format()]: util.html#util_util_format_format [`console.log()`]: #console_console_log_data
[`console.timeEnd()`]: #console_console_timeend_label
[`console.time()`]: #console_console_time_label [`console.time()`]: #console_console_time_label
[`console.timeEnd()`]: #console_console_timeend_label
[`util.format()`]: util.html#util_util_format_format
[`util.inspect()`]: util.html#util_util_inspect_object_options
[customizing `util.inspect()` colors]: util.html#util_customizing_util_inspect_colors

59
doc/api/crypto.markdown

@ -89,7 +89,7 @@ data as it is streamed.
Class for decrypting data. Class for decrypting data.
Returned by `crypto.createDecipher` and `crypto.createDecipheriv`. Returned by [`crypto.createDecipher`][] and [`crypto.createDecipheriv`][].
Decipher objects are [streams][] that are both readable and writable. Decipher objects are [streams][] that are both readable and writable.
The written enciphered data is used to produce the plain-text data on The written enciphered data is used to produce the plain-text data on
@ -125,7 +125,7 @@ You can disable auto padding if the data has been encrypted without
standard block padding to prevent `decipher.final` from checking and standard block padding to prevent `decipher.final` from checking and
removing it. This will only work if the input data's length is a multiple of removing it. This will only work if the input data's length is a multiple of
the ciphers block size. You must call this before streaming data to the ciphers block size. You must call this before streaming data to
`decipher.update`. [`decipher.update`][].
### decipher.update(data[, input_encoding][, output_encoding]) ### decipher.update(data[, input_encoding][, output_encoding])
@ -426,15 +426,15 @@ is used to compute the hash. Once the writable side of the stream is ended,
use the `read()` method to get the enciphered contents. The legacy `update` use the `read()` method to get the enciphered contents. The legacy `update`
and `final` methods are also supported. and `final` methods are also supported.
Note: `createCipher` derives keys with the OpenSSL function [EVP_BytesToKey][] Note: `createCipher` derives keys with the OpenSSL function [`EVP_BytesToKey`][]
with the digest algorithm set to MD5, one iteration, and no salt. The lack of with the digest algorithm set to MD5, one iteration, and no salt. The lack of
salt allows dictionary attacks as the same password always creates the same key. salt allows dictionary attacks as the same password always creates the same key.
The low iteration count and non-cryptographically secure hash algorithm allow The low iteration count and non-cryptographically secure hash algorithm allow
passwords to be tested very rapidly. passwords to be tested very rapidly.
In line with OpenSSL's recommendation to use pbkdf2 instead of EVP_BytesToKey it In line with OpenSSL's recommendation to use pbkdf2 instead of [`EVP_BytesToKey`][] it
is recommended you derive a key and iv yourself with [crypto.pbkdf2][] and to is recommended you derive a key and iv yourself with [`crypto.pbkdf2`][] and to
then use [createCipheriv()][] to create the cipher stream. then use [`createCipheriv()`][] to create the cipher stream.
## crypto.createCipheriv(algorithm, key, iv) ## crypto.createCipheriv(algorithm, key, iv)
@ -448,7 +448,7 @@ the raw key used by the algorithm. `iv` is an [initialization vector][].
## crypto.createCredentials(details) ## crypto.createCredentials(details)
Stability: 0 - Deprecated: Use [tls.createSecureContext][] instead. Stability: 0 - Deprecated: Use [`tls.createSecureContext`][] instead.
Creates a credentials object, with the optional details being a Creates a credentials object, with the optional details being a
dictionary with keys: dictionary with keys:
@ -474,12 +474,12 @@ publicly trusted list of CAs as given in
## crypto.createDecipher(algorithm, password) ## crypto.createDecipher(algorithm, password)
Creates and returns a decipher object, with the given algorithm and Creates and returns a decipher object, with the given algorithm and
key. This is the mirror of the [createCipher()][] above. key. This is the mirror of the [`createCipher()`][] above.
## crypto.createDecipheriv(algorithm, key, iv) ## crypto.createDecipheriv(algorithm, key, iv)
Creates and returns a decipher object, with the given algorithm, key Creates and returns a decipher object, with the given algorithm, key
and iv. This is the mirror of the [createCipheriv()][] above. and iv. This is the mirror of the [`createCipheriv()`][] above.
## crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding]) ## crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])
@ -500,7 +500,7 @@ If no `generator` is specified, then `2` is used.
## crypto.createECDH(curve_name) ## crypto.createECDH(curve_name)
Creates an Elliptic Curve (EC) Diffie-Hellman key exchange object using a Creates an Elliptic Curve (EC) Diffie-Hellman key exchange object using a
predefined curve specified by the `curve_name` string. Use [getCurves()][] to predefined curve specified by the `curve_name` string. Use [`getCurves()`][] to
obtain a list of available curve names. On recent releases, obtain a list of available curve names. On recent releases,
`openssl ecparam -list_curves` will also display the name and description of `openssl ecparam -list_curves` will also display the name and description of
each available elliptic curve. each available elliptic curve.
@ -583,8 +583,8 @@ supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in
[RFC 2412][], but see [Caveats][]) and `'modp14'`, `'modp15'`, [RFC 2412][], but see [Caveats][]) and `'modp14'`, `'modp15'`,
`'modp16'`, `'modp17'`, `'modp18'` (defined in [RFC 3526][]). The `'modp16'`, `'modp17'`, `'modp18'` (defined in [RFC 3526][]). The
returned object mimics the interface of objects created by returned object mimics the interface of objects created by
[crypto.createDiffieHellman()][] above, but will not allow changing [`crypto.createDiffieHellman()`][] above, but will not allow changing
the keys (with [diffieHellman.setPublicKey()][] for example). The the keys (with [`diffieHellman.setPublicKey()`][] for example). The
advantage of using this routine is that the parties do not have to advantage of using this routine is that the parties do not have to
generate nor exchange group modulus beforehand, saving both processor generate nor exchange group modulus beforehand, saving both processor
and communication time. and communication time.
@ -635,7 +635,7 @@ Example:
console.log(key.toString('hex')); // 'c5e478d...1469e50' console.log(key.toString('hex')); // 'c5e478d...1469e50'
}); });
You can get a list of supported digest functions with [crypto.getHashes()][]. You can get a list of supported digest functions with [`crypto.getHashes()`][].
## crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest]) ## crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])
@ -782,22 +782,25 @@ Based on the recommendations of [NIST SP 800-131A]:
See the reference for other recommendations and details. See the reference for other recommendations and details.
[stream]: stream.html [`createCipher()`]: #crypto_crypto_createcipher_algorithm_password
[streams]: stream.html [`createCipheriv()`]: #crypto_crypto_createcipheriv_algorithm_key_iv
[`crypto.createDecipher`]: #crypto_crypto_createdecipher_algorithm_password
[`crypto.createDecipheriv`]: #crypto_crypto_createdecipheriv_algorithm_key_iv
[`crypto.createDiffieHellman()`]: #crypto_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding
[`crypto.getHashes()`]: #crypto_crypto_gethashes
[`crypto.pbkdf2`]: #crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback
[`decipher.update`]: #crypto_decipher_update_data_input_encoding_output_encoding
[`diffieHellman.setPublicKey()`]: #crypto_diffiehellman_setpublickey_public_key_encoding
[`EVP_BytesToKey`]: https://www.openssl.org/docs/crypto/EVP_BytesToKey.html
[`getCurves()`]: #crypto_crypto_getcurves
[`tls.createSecureContext`]: tls.html#tls_tls_createsecurecontext_details
[buffer]: buffer.html [buffer]: buffer.html
[buffers]: buffer.html [buffers]: buffer.html
[createCipher()]: #crypto_crypto_createcipher_algorithm_password [Caveats]: #crypto_caveats
[createCipheriv()]: #crypto_crypto_createcipheriv_algorithm_key_iv [initialization vector]: http://en.wikipedia.org/wiki/Initialization_vector
[getCurves()]: #crypto_crypto_getcurves [NIST SP 800-131A]: http://csrc.nist.gov/publications/nistpubs/800-131A/sp800-131A.pdf
[crypto.createDiffieHellman()]: #crypto_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding [NIST SP 800-132]: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
[tls.createSecureContext]: tls.html#tls_tls_createsecurecontext_details
[diffieHellman.setPublicKey()]: #crypto_diffiehellman_setpublickey_public_key_encoding
[RFC 2412]: http://www.rfc-editor.org/rfc/rfc2412.txt [RFC 2412]: http://www.rfc-editor.org/rfc/rfc2412.txt
[RFC 3526]: http://www.rfc-editor.org/rfc/rfc3526.txt [RFC 3526]: http://www.rfc-editor.org/rfc/rfc3526.txt
[crypto.pbkdf2]: #crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback [stream]: stream.html
[EVP_BytesToKey]: https://www.openssl.org/docs/crypto/EVP_BytesToKey.html [streams]: stream.html
[NIST SP 800-132]: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
[NIST SP 800-131A]: http://csrc.nist.gov/publications/nistpubs/800-131A/sp800-131A.pdf
[initialization vector]: http://en.wikipedia.org/wiki/Initialization_vector
[Caveats]: #crypto_caveats
[crypto.getHashes()]: #crypto_crypto_gethashes

56
doc/api/dgram.markdown

@ -6,7 +6,7 @@
Datagram sockets are available through `require('dgram')`. Datagram sockets are available through `require('dgram')`.
Important note: the behavior of `dgram.Socket#bind()` has changed in v0.10 Important note: the behavior of [`dgram.Socket#bind()`][] has changed in v0.10
and is always asynchronous now. If you have code that looks like this: and is always asynchronous now. If you have code that looks like this:
var s = dgram.createSocket('udp4'); var s = dgram.createSocket('udp4');
@ -23,11 +23,11 @@ You have to change it to this:
## Class: dgram.Socket ## Class: dgram.Socket
The dgram Socket class encapsulates the datagram functionality. It The dgram Socket class encapsulates the datagram functionality. It
should be created via `dgram.createSocket(...)` should be created via [`dgram.createSocket(...)`][]
### Event: 'close' ### Event: 'close'
Emitted after a socket is closed with `close()`. No new `message` events will be emitted Emitted after a socket is closed with [`close()`][]. No new `'message'` events will be emitted
on this socket. on this socket.
### Event: 'error' ### Event: 'error'
@ -79,16 +79,16 @@ this object will contain `address` , `family` and `port`.
For UDP sockets, listen for datagrams on a named `port` and optional For UDP sockets, listen for datagrams on a named `port` and optional
`address`. If `port` is not specified, the OS will try to bind to a random `address`. If `port` is not specified, the OS will try to bind to a random
port. If `address` is not specified, the OS will try to listen on port. If `address` is not specified, the OS will try to listen on
all addresses. After binding is done, a "listening" event is emitted all addresses. After binding is done, a `'listening'` event is emitted
and the `callback`(if specified) is called. Specifying both a and the `callback`(if specified) is called. Specifying both a
"listening" event listener and `callback` is not harmful but not very `'listening'` event listener and `callback` is not harmful but not very
useful. useful.
A bound datagram socket keeps the Node.js process running to receive A bound datagram socket keeps the Node.js process running to receive
datagrams. datagrams.
If binding fails, an "error" event is generated. In rare case (e.g. If binding fails, an `'error'` event is generated. In rare case (e.g.
binding a closed socket), an `Error` may be thrown by this method. binding a closed socket), an [`Error`][] may be thrown by this method.
Example of a UDP server listening on port 41234: Example of a UDP server listening on port 41234:
@ -125,8 +125,7 @@ Example of a UDP server listening on port 41234:
The `port` and `address` properties of `options`, as well as the optional The `port` and `address` properties of `options`, as well as the optional
callback function, behave as they do on a call to callback function, behave as they do on a call to
[socket.bind(port, \[address\], \[callback\]) [`socket.bind(port, \[address\], \[callback\])`][].
](#dgram_socket_bind_port_address_callback).
If `exclusive` is `false` (default), then cluster workers will use the same If `exclusive` is `false` (default), then cluster workers will use the same
underlying handle, allowing connection handling duties to be shared. When underlying handle, allowing connection handling duties to be shared. When
@ -143,14 +142,14 @@ shown below.
### socket.close([callback]) ### socket.close([callback])
Close the underlying socket and stop listening for data on it. If a callback is Close the underlying socket and stop listening for data on it. If a callback is
provided, it is added as a listener for the ['close'][] event. provided, it is added as a listener for the [`'close'`][] event.
### socket.dropMembership(multicastAddress[, multicastInterface]) ### socket.dropMembership(multicastAddress[, multicastInterface])
* `multicastAddress` String * `multicastAddress` String
* `multicastInterface` String, Optional * `multicastInterface` String, Optional
Opposite of `addMembership` - tells the kernel to leave a multicast group with Opposite of [`addMembership()`][] - tells the kernel to leave a multicast group with
`IP_DROP_MEMBERSHIP` socket option. This is automatically called by the kernel `IP_DROP_MEMBERSHIP` socket option. This is automatically called by the kernel
when the socket is closed or process terminates, so most apps will never need to call when the socket is closed or process terminates, so most apps will never need to call
this. this.
@ -241,7 +240,7 @@ packets will also be received on the local interface.
* `ttl` Integer * `ttl` Integer
Sets the `IP_MULTICAST_TTL` socket option. TTL stands for "Time to Live," but in this Sets the `IP_MULTICAST_TTL` socket option. TTL stands for "Time to Live", but in this
context it specifies the number of IP hops that a packet is allowed to go through, context it specifies the number of IP hops that a packet is allowed to go through,
specifically for multicast traffic. Each router or gateway that forwards a packet specifically for multicast traffic. Each router or gateway that forwards a packet
decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
@ -253,7 +252,7 @@ systems is 1.
* `ttl` Integer * `ttl` Integer
Sets the `IP_TTL` socket option. TTL stands for "Time to Live," but in this context it Sets the `IP_TTL` socket option. TTL stands for "Time to Live", but in this context it
specifies the number of IP hops that a packet is allowed to go through. Each router or specifies the number of IP hops that a packet is allowed to go through. Each router or
gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a
router, it will not be forwarded. Changing TTL values is typically done for network router, it will not be forwarded. Changing TTL values is typically done for network
@ -280,39 +279,48 @@ Returns `socket`.
## dgram.createSocket(options[, callback]) ## dgram.createSocket(options[, callback])
* `options` Object * `options` Object
* `callback` Function. Attached as a listener to `message` events. * `callback` Function. Attached as a listener to `'message'` events.
* Returns: Socket object * Returns: Socket object
The `options` object should contain a `type` field of either `udp4` or `udp6` The `options` object should contain a `type` field of either `udp4` or `udp6`
and an optional boolean `reuseAddr` field. and an optional boolean `reuseAddr` field.
When `reuseAddr` is `true` `socket.bind()` will reuse the address, even if When `reuseAddr` is `true` [`socket.bind()`][] will reuse the address, even if
another process has already bound a socket on it. `reuseAddr` defaults to another process has already bound a socket on it. `reuseAddr` defaults to
`false`. `false`.
Takes an optional callback which is added as a listener for `message` events. Takes an optional callback which is added as a listener for `'message'` events.
Call `socket.bind()` if you want to receive datagrams. `socket.bind()` will Call [`socket.bind()`][] if you want to receive datagrams. [`socket.bind()`][] will
bind to the "all interfaces" address on a random port (it does the right thing bind to the "all interfaces" address on a random port (it does the right thing
for both `udp4` and `udp6` sockets). You can then retrieve the address and port for both `udp4` and `udp6` sockets). You can then retrieve the address and port
with `socket.address().address` and `socket.address().port`. with [`socket.address().address`][] and [`socket.address().port`][].
## dgram.createSocket(type[, callback]) ## dgram.createSocket(type[, callback])
* `type` String. Either 'udp4' or 'udp6' * `type` String. Either 'udp4' or 'udp6'
* `callback` Function. Attached as a listener to `message` events. * `callback` Function. Attached as a listener to `'message'` events.
Optional Optional
* Returns: Socket object * Returns: Socket object
Creates a datagram Socket of the specified types. Valid types are `udp4` Creates a datagram Socket of the specified types. Valid types are `udp4`
and `udp6`. and `udp6`.
Takes an optional callback which is added as a listener for `message` events. Takes an optional callback which is added as a listener for `'message'` events.
Call `socket.bind()` if you want to receive datagrams. `socket.bind()` will Call [`socket.bind()`][] if you want to receive datagrams. [`socket.bind()`][] will
bind to the "all interfaces" address on a random port (it does the right thing bind to the "all interfaces" address on a random port (it does the right thing
for both `udp4` and `udp6` sockets). You can then retrieve the address and port for both `udp4` and `udp6` sockets). You can then retrieve the address and port
with `socket.address().address` and `socket.address().port`. with [`socket.address().address`][] and [`socket.address().port`][].
['close']: #dgram_event_close [`'close'`]: #dgram_event_close
[`addMembership()`]: #dgram_socket_addmembership_multicastaddress_multicastinterface
[`close()`]: #dgram_socket_close_callback
[`dgram.createSocket(...)`]: #dgram_dgram_createsocket_options_callback
[`dgram.Socket#bind()`]: #dgram_socket_bind_options_callback
[`Error`]: errors.html#errors_class_error
[`socket.address().address`]: #dgram_socket_address
[`socket.address().port`]: #dgram_socket_address
[`socket.bind()`]: #dgram_socket_bind_port_address_callback
[`socket.bind(port, \[address\], \[callback\])`]: #dgram_socket_bind_port_address_callback
[byte length]: buffer.html#buffer_class_method_buffer_bytelength_string_encoding [byte length]: buffer.html#buffer_class_method_buffer_bytelength_string_encoding

34
doc/api/dns.markdown

@ -8,7 +8,7 @@ This module contains functions that belong to two different categories:
1) Functions that use the underlying operating system facilities to perform 1) Functions that use the underlying operating system facilities to perform
name resolution, and that do not necessarily do any network communication. name resolution, and that do not necessarily do any network communication.
This category contains only one function: `dns.lookup()`. __Developers looking This category contains only one function: [`dns.lookup()`][]. __Developers looking
to perform name resolution in the same way that other applications on the same to perform name resolution in the same way that other applications on the same
operating system behave should use [`dns.lookup()`][].__ operating system behave should use [`dns.lookup()`][].__
@ -97,7 +97,7 @@ With the `all` option set, the arguments change to `(err, addresses)`, with
`addresses` being an array of objects with the properties `address` and `addresses` being an array of objects with the properties `address` and
`family`. `family`.
On error, `err` is an `Error` object, where `err.code` is the error code. On error, `err` is an [`Error`][] object, where `err.code` is the error code.
Keep in mind that `err.code` will be set to `'ENOENT'` not only when Keep in mind that `err.code` will be set to `'ENOENT'` not only when
the hostname does not exist but also when the lookup fails in other ways the hostname does not exist but also when the lookup fails in other ways
such as no available file descriptors. such as no available file descriptors.
@ -118,7 +118,7 @@ Resolves the given address and port into a hostname and service using
The callback has arguments `(err, hostname, service)`. The `hostname` and The callback has arguments `(err, hostname, service)`. The `hostname` and
`service` arguments are strings (e.g. `'localhost'` and `'http'` respectively). `service` arguments are strings (e.g. `'localhost'` and `'http'` respectively).
On error, `err` is an `Error` object, where `err.code` is the error code. On error, `err` is an [`Error`][] object, where `err.code` is the error code.
## dns.resolve(hostname[, rrtype], callback) ## dns.resolve(hostname[, rrtype], callback)
@ -142,7 +142,7 @@ The callback has arguments `(err, addresses)`. The type of each item
in `addresses` is determined by the record type, and described in the in `addresses` is determined by the record type, and described in the
documentation for the corresponding lookup methods below. documentation for the corresponding lookup methods below.
On error, `err` is an `Error` object, where `err.code` is On error, `err` is an [`Error`][] object, where `err.code` is
one of the error codes listed below. one of the error codes listed below.
@ -215,7 +215,7 @@ Reverse resolves an ip address to an array of hostnames.
The callback has arguments `(err, hostnames)`. The callback has arguments `(err, hostnames)`.
On error, `err` is an `Error` object, where `err.code` is On error, `err` is an [`Error`][] object, where `err.code` is
one of the error codes listed below. one of the error codes listed below.
## dns.setServers(servers) ## dns.setServers(servers)
@ -259,7 +259,7 @@ Each DNS query can return one of the following error codes:
## Supported getaddrinfo flags ## Supported getaddrinfo flags
The following flags can be passed as hints to `dns.lookup()`. The following flags can be passed as hints to [`dns.lookup()`][].
- `dns.ADDRCONFIG`: Returned address types are determined by the types - `dns.ADDRCONFIG`: Returned address types are determined by the types
of addresses supported by the current system. For example, IPv4 addresses of addresses supported by the current system. For example, IPv4 addresses
@ -271,17 +271,17 @@ on some operating systems (e.g FreeBSD 10.1).
## Implementation considerations ## Implementation considerations
Although `dns.lookup()` and `dns.resolve*()/dns.reverse()` functions have the same Although [`dns.lookup()`][] and `dns.resolve*()/dns.reverse()` functions have the same
goal of associating a network name with a network address (or vice versa), goal of associating a network name with a network address (or vice versa),
their behavior is quite different. These differences can have subtle but their behavior is quite different. These differences can have subtle but
significant consequences on the behavior of Node.js programs. significant consequences on the behavior of Node.js programs.
### dns.lookup ### dns.lookup
Under the hood, `dns.lookup()` uses the same operating system facilities as most Under the hood, [`dns.lookup()`][] uses the same operating system facilities as most
other programs. For instance, `dns.lookup()` will almost always resolve a given other programs. For instance, [`dns.lookup()`][] will almost always resolve a given
name the same way as the `ping` command. On most POSIX-like operating systems, name the same way as the `ping` command. On most POSIX-like operating systems,
the behavior of the `dns.lookup()` function can be tweaked by changing settings the behavior of the [`dns.lookup()`][] function can be tweaked by changing settings
in `nsswitch.conf(5)` and/or `resolv.conf(5)`, but be careful that changing in `nsswitch.conf(5)` and/or `resolv.conf(5)`, but be careful that changing
these files will change the behavior of all other programs running on the same these files will change the behavior of all other programs running on the same
operating system. operating system.
@ -299,21 +299,21 @@ setting the 'UV_THREADPOOL_SIZE' environment variable to a value greater than
### dns.resolve, functions starting with dns.resolve and dns.reverse ### dns.resolve, functions starting with dns.resolve and dns.reverse
These functions are implemented quite differently than `dns.lookup()`. They do These functions are implemented quite differently than [`dns.lookup()`][]. They do
not use `getaddrinfo(3)` and they _always_ perform a DNS query on the network. not use `getaddrinfo(3)` and they _always_ perform a DNS query on the network.
This network communication is always done asynchronously, and does not use This network communication is always done asynchronously, and does not use
libuv's threadpool. libuv's threadpool.
As a result, these functions cannot have the same negative impact on other As a result, these functions cannot have the same negative impact on other
processing that happens on libuv's threadpool that `dns.lookup()` can have. processing that happens on libuv's threadpool that [`dns.lookup()`][] can have.
They do not use the same set of configuration files than what `dns.lookup()` They do not use the same set of configuration files than what [`dns.lookup()`][]
uses. For instance, _they do not use the configuration from `/etc/hosts`_. uses. For instance, _they do not use the configuration from `/etc/hosts`_.
[Implementation considerations section]: #dns_implementation_considerations [`dns.lookup()`]: #dns_dns_lookup_hostname_options_callback
[supported `getaddrinfo` flags]: #dns_supported_getaddrinfo_flags
[`dns.resolve()`]: #dns_dns_resolve_hostname_rrtype_callback [`dns.resolve()`]: #dns_dns_resolve_hostname_rrtype_callback
[`dns.resolve4()`]: #dns_dns_resolve4_hostname_callback [`dns.resolve4()`]: #dns_dns_resolve4_hostname_callback
[`Error`]: errors.html#errors_class_error
[Implementation considerations section]: #dns_implementation_considerations
[supported `getaddrinfo` flags]: #dns_supported_getaddrinfo_flags
[the official libuv documentation]: http://docs.libuv.org/en/latest/threadpool.html [the official libuv documentation]: http://docs.libuv.org/en/latest/threadpool.html
[`dns.lookup()`]: #dns_dns_lookup_hostname_options_callback

52
doc/api/domain.markdown

@ -11,7 +11,7 @@ in the future.
Domains provide a way to handle multiple different IO operations as a Domains provide a way to handle multiple different IO operations as a
single group. If any of the event emitters or callbacks registered to a single group. If any of the event emitters or callbacks registered to a
domain emit an `error` event, or throw an error, then the domain object domain emit an `'error'` event, or throw an error, then the domain object
will be notified, rather than losing the context of the error in the will be notified, rather than losing the context of the error in the
`process.on('uncaughtException')` handler, or causing the program to `process.on('uncaughtException')` handler, or causing the program to
exit immediately with an error code. exit immediately with an error code.
@ -23,7 +23,7 @@ exit immediately with an error code.
Domain error handlers are not a substitute for closing down your Domain error handlers are not a substitute for closing down your
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
never any way to safely "pick up where you left off", without leaking 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.
@ -174,11 +174,11 @@ function handleRequest(req, res) {
<!-- type=misc --> <!-- type=misc -->
Any time an Error object is routed through a domain, a few extra fields Any time an `Error` object is routed through a domain, a few extra fields
are added to it. are added to it.
* `error.domain` The domain that first handled the error. * `error.domain` The domain that first handled the error.
* `error.domainEmitter` The event emitter that emitted an 'error' event * `error.domainEmitter` The event emitter that emitted an `'error'` event
with the error object. with the error object.
* `error.domainBound` The callback function which was bound to the * `error.domainBound` The callback function which was bound to the
domain, and passed an error as its first argument. domain, and passed an error as its first argument.
@ -207,8 +207,8 @@ If you *want* to nest Domain objects as children of a parent Domain,
then you must explicitly add them. then you must explicitly add them.
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
Domain, so `domain.dispose()` will not shut down the EventEmitter. Domain, so [`domain.dispose()`][] will not shut down the EventEmitter.
Implicit binding only takes care of thrown errors and `'error'` events. Implicit binding only takes care of thrown errors and `'error'` events.
## Explicit Binding ## Explicit Binding
@ -264,8 +264,8 @@ Returns a new Domain object.
The Domain class encapsulates the functionality of routing errors and The Domain class encapsulates the functionality of routing errors and
uncaught exceptions to the active Domain object. uncaught exceptions to the active Domain object.
Domain is a child class of [EventEmitter][]. To handle the errors that it Domain is a child class of [`EventEmitter`][]. To handle the errors that it
catches, listen to its `error` event. catches, listen to its `'error'` event.
### domain.run(fn[, arg][, ...]) ### domain.run(fn[, arg][, ...])
@ -312,12 +312,12 @@ to the domain.
* `emitter` {EventEmitter | Timer} emitter or timer to be added to the domain * `emitter` {EventEmitter | Timer} emitter or timer to be added to the domain
Explicitly adds an emitter to the domain. If any event handlers called by Explicitly adds an emitter to the domain. If any event handlers called by
the emitter throw an error, or if the emitter emits an `error` event, it the emitter throw an error, or if the emitter emits an `'error'` event, it
will be routed to the domain's `error` event, just like with implicit will be routed to the domain's `'error'` event, just like with implicit
binding. binding.
This also works with timers that are returned from `setInterval` and This also works with timers that are returned from [`setInterval()`][] and
`setTimeout`. If their callback function throws, it will be caught by [`setTimeout()`][]. If their callback function throws, it will be caught by
the domain 'error' handler. the domain 'error' handler.
If the Timer or EventEmitter was already bound to a domain, it is removed If the Timer or EventEmitter was already bound to a domain, it is removed
@ -327,7 +327,7 @@ from that one, and bound to this one instead.
* `emitter` {EventEmitter | Timer} emitter or timer to be removed from the domain * `emitter` {EventEmitter | Timer} emitter or timer to be removed from the domain
The opposite of `domain.add(emitter)`. Removes domain handling from the The opposite of [`domain.add(emitter)`][]. Removes domain handling from the
specified emitter. specified emitter.
### domain.bind(callback) ### domain.bind(callback)
@ -337,7 +337,7 @@ specified emitter.
The returned function will be a wrapper around the supplied callback The returned function will be a wrapper around the supplied callback
function. When the returned function is called, any errors that are function. When the returned function is called, any errors that are
thrown will be routed to the domain's `error` event. thrown will be routed to the domain's `'error'` event.
#### Example #### Example
@ -361,11 +361,11 @@ thrown will be routed to the domain's `error` event.
* `callback` {Function} The callback function * `callback` {Function} The callback function
* return: {Function} The intercepted function * return: {Function} The intercepted function
This method is almost identical to `domain.bind(callback)`. However, in This method is almost identical to [`domain.bind(callback)`][]. However, in
addition to catching thrown errors, it will also intercept `Error` addition to catching thrown errors, it will also intercept [`Error`][]
objects sent as the first argument to the function. objects sent as the first argument to the function.
In this way, the common `if (er) return callback(er);` pattern can be replaced In this way, the common `if (err) return callback(err);` pattern can be replaced
with a single error handler in a single place. with a single error handler in a single place.
#### Example #### Example
@ -397,12 +397,12 @@ with a single error handler in a single place.
The `enter` method is plumbing used by the `run`, `bind`, and `intercept` The `enter` method is plumbing used by the `run`, `bind`, and `intercept`
methods to set the active domain. It sets `domain.active` and `process.domain` methods to set the active domain. It sets `domain.active` and `process.domain`
to the domain, and implicitly pushes the domain onto the domain stack managed to the domain, and implicitly pushes the domain onto the domain stack managed
by the domain module (see `domain.exit()` for details on the domain stack). The by the domain module (see [`domain.exit()`][] for details on the domain stack). The
call to `enter` delimits the beginning of a chain of asynchronous calls and I/O call to `enter` delimits the beginning of a chain of asynchronous calls and I/O
operations bound to a domain. operations bound to a domain.
Calling `enter` changes only the active domain, and does not alter the domain Calling `enter` changes only the active domain, and does not alter the domain
itself. `Enter` and `exit` can be called an arbitrary number of times on a itself. `enter` and `exit` can be called an arbitrary number of times on a
single domain. single domain.
If the domain on which `enter` is called has been disposed, `enter` will return If the domain on which `enter` is called has been disposed, `enter` will return
@ -420,7 +420,7 @@ If there are multiple, nested domains bound to the current execution context,
`exit` will exit any domains nested within this domain. `exit` will exit any domains nested within this domain.
Calling `exit` changes only the active domain, and does not alter the domain Calling `exit` changes only the active domain, and does not alter the domain
itself. `Enter` and `exit` can be called an arbitrary number of times on a itself. `enter` and `exit` can be called an arbitrary number of times on a
single domain. single domain.
If the domain on which `exit` is called has been disposed, `exit` will return If the domain on which `exit` is called has been disposed, `exit` will return
@ -432,7 +432,15 @@ without exiting the domain.
explicitly via error event handlers set on the domain. explicitly via error event handlers set on the domain.
Once `dispose` has been called, the domain will no longer be used by callbacks Once `dispose` has been called, the domain will no longer be used by callbacks
bound into the domain via `run`, `bind`, or `intercept`, and a `dispose` event bound into the domain via `run`, `bind`, or `intercept`, and a `'dispose'` event
is emitted. is emitted.
[EventEmitter]: events.html#events_class_events_eventemitter [`domain.add(emitter)`]: #domain_domain_add_emitter
[`domain.bind(callback)`]: #domain_domain_bind_callback
[`domain.dispose()`]: #domain_domain_dispose
[`domain.exit()`]: #domain_domain_exit
[`Error`]: errors.html#errors_class_error
[`EventEmitter`]: events.html#events_class_events_eventemitter
[`setInterval()`]: timers.html#timers_setinterval_callback_delay_arg
[`setTimeout()`]: timers.html#timers_settimeout_callback_delay_arg
[`throw`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw

82
doc/api/errors.markdown

@ -3,7 +3,7 @@
<!--type=misc--> <!--type=misc-->
Errors generated by Node.js fall into two categories: JavaScript errors and system Errors generated by Node.js fall into two categories: JavaScript errors and system
errors. All errors inherit from or are instances of JavaScript's [Error][] errors. All errors inherit from or are instances of JavaScript's [`Error`][]
class and are guaranteed to provide *at least* the attributes available on that class and are guaranteed to provide *at least* the attributes available on that
class. class.
@ -15,7 +15,7 @@ opportunity to **intercept** this error based on how the API **propagates** it.
The style of API called determines how generated errors are handed back, or The style of API called determines how generated errors are handed back, or
**propagated**, to client code, which in turn informs how the client may **intercept** **propagated**, to client code, which in turn informs how the client may **intercept**
the error. Exceptions can be intercepted using the `try / catch` construct; the error. Exceptions can be intercepted using the [`try / catch` construct][];
other propagation strategies are covered [below][]. other propagation strategies are covered [below][].
## Error Propagation and Interception ## Error Propagation and Interception
@ -26,9 +26,9 @@ All Node.js APIs will treat invalid arguments as exceptional -- that is, if pass
invalid arguments, they will *immediately* generate and throw the error as an invalid arguments, they will *immediately* generate and throw the error as an
exception, even if they are an otherwise asynchronous API. exception, even if they are an otherwise asynchronous API.
Synchronous APIs (like [fs.readFileSync][]) will throw the error. The act of Synchronous APIs (like [`fs.readFileSync`][]) will throw the error. The act of
*throwing* a value (in this case, the error) turns the value into an **exception**. *throwing* a value (in this case, the error) turns the value into an **exception**.
Exceptions may be caught using the `try { } catch(err) { }` construct. Exceptions may be caught using the [`try { } catch(err) { }`][] construct.
Asynchronous APIs have **two** mechanisms for error propagation; one mechanism Asynchronous APIs have **two** mechanisms for error propagation; one mechanism
for APIs that represent a single operation, and one for APIs that represent for APIs that represent a single operation, and one for APIs that represent
@ -38,20 +38,20 @@ multiple operations over time.
<!--type=misc--> <!--type=misc-->
The other mechanism for providing errors is the "error" event. This is The other mechanism for providing errors is the `'error'` event. This is
typically used by [stream-based][] and [event emitter-based][] APIs, which typically used by [stream-based][] and [event emitter-based][] APIs, which
themselves represent a series of asynchronous operations over time (versus a themselves represent a series of asynchronous operations over time (versus a
single operation that may pass or fail). If no "error" event handler is single operation that may pass or fail). If no `'error'` event handler is
attached to the source of the error, the error will be thrown. At this point, attached to the source of the error, the error will be thrown. At this point,
it will crash the process as an unhandled exception unless [domains][] are it will crash the process as an unhandled exception unless [domains][] are
employed appropriately or [process.on('uncaughtException')][] has a handler. employed appropriately or [`process.on('uncaughtException')`][] has a handler.
```javascript ```javascript
var net = require('net'); var net = require('net');
var connection = net.connect('localhost'); var connection = net.connect('localhost');
// adding an "error" event handler to a stream: // adding an 'error' event handler to a stream:
connection.on('error', function(err) { connection.on('error', function(err) {
// if the connection is reset by the server, or if it can't // if the connection is reset by the server, or if it can't
// connect at all, or on any sort of error encountered by // connect at all, or on any sort of error encountered by
@ -72,7 +72,7 @@ var EventEmitter = require('events');
var ee = new EventEmitter(); var ee = new EventEmitter();
setImmediate(function() { setImmediate(function() {
// this will crash the process because no "error" event // this will crash the process because no 'error' event
// handler has been added. // handler has been added.
ee.emit('error', new Error('This will crash')); ee.emit('error', new Error('This will crash'));
}); });
@ -154,7 +154,7 @@ errors as well as plain JavaScript errors.
#### new Error(message) #### new Error(message)
Instantiates a new Error object and sets its `.message` property to the provided Instantiates a new `Error` object and sets its `.message` property to the provided
message. Its `.stack` will represent the point in the program at which `new Error` message. Its `.stack` will represent the point in the program at which `new Error`
was called. Stack traces are subject to [V8's stack trace API][]. was called. Stack traces are subject to [V8's stack trace API][].
Stack traces only extend to the beginning of synchronous code execution, *or* a number of frames given by Stack traces only extend to the beginning of synchronous code execution, *or* a number of frames given by
@ -279,12 +279,12 @@ The number of frames captured by the stack trace is bounded by the smaller of
`Error.stackTraceLimit` or the number of available frames on the current event `Error.stackTraceLimit` or the number of available frames on the current event
loop tick. loop tick.
System-level errors are generated as augmented Error instances, which are detailed System-level errors are generated as augmented `Error` instances, which are detailed
[below](#errors_system_errors). [below](#errors_system_errors).
### Class: RangeError ### Class: RangeError
A subclass of Error that indicates that a provided argument was not within the A subclass of `Error` that indicates that a provided argument was not within the
set or range of acceptable values for a function; whether that be a numeric set or range of acceptable values for a function; whether that be a numeric
range, or outside the set of options for a given function parameter. An example: range, or outside the set of options for a given function parameter. An example:
@ -292,12 +292,12 @@ range, or outside the set of options for a given function parameter. An example:
require('net').connect(-1); // throws RangeError, port should be > 0 && < 65536 require('net').connect(-1); // throws RangeError, port should be > 0 && < 65536
``` ```
Node.js will generate and throw RangeError instances *immediately* -- they are a form Node.js will generate and throw `RangeError` instances *immediately* -- they are a form
of argument validation. of argument validation.
### Class: ReferenceError ### Class: ReferenceError
A subclass of Error that indicates that an attempt is being made to access a variable A subclass of `Error` that indicates that an attempt is being made to access a variable
that is not defined. Most commonly it indicates a typo, or an otherwise broken program. that is not defined. Most commonly it indicates a typo, or an otherwise broken program.
While client code may generate and propagate these errors, in practice only V8 will do While client code may generate and propagate these errors, in practice only V8 will do
so. so.
@ -306,7 +306,7 @@ so.
doesNotExist; // throws ReferenceError, doesNotExist is not a variable in this program. doesNotExist; // throws ReferenceError, doesNotExist is not a variable in this program.
``` ```
ReferenceError instances will have an `.arguments` member that is an array containing `ReferenceError` instances will have an `.arguments` member that is an array containing
one element -- a string representing the variable that was not defined. one element -- a string representing the variable that was not defined.
```javascript ```javascript
@ -323,7 +323,7 @@ dependencies.
### Class: SyntaxError ### Class: SyntaxError
A subclass of Error that indicates that a program is not valid JavaScript. A subclass of `Error` that indicates that a program is not valid JavaScript.
These errors may only be generated and propagated as a result of code These errors may only be generated and propagated as a result of code
evaluation. Code evaluation may happen as a result of `eval`, `Function`, evaluation. Code evaluation may happen as a result of `eval`, `Function`,
`require`, or [vm][]. These errors are almost always indicative of a broken `require`, or [vm][]. These errors are almost always indicative of a broken
@ -342,7 +342,7 @@ by other contexts.
### Class: TypeError ### Class: TypeError
A subclass of Error that indicates that a provided argument is not an allowable A subclass of `Error` that indicates that a provided argument is not an allowable
type. For example, passing a function to a parameter which expects a string would type. For example, passing a function to a parameter which expects a string would
be considered a TypeError. be considered a TypeError.
@ -350,7 +350,7 @@ be considered a TypeError.
require('url').parse(function() { }); // throws TypeError, since it expected a string require('url').parse(function() { }); // throws TypeError, since it expected a string
``` ```
Node.js will generate and throw TypeError instances *immediately* -- they are a form Node.js will generate and throw `TypeError` instances *immediately* -- they are a form
of argument validation. of argument validation.
### Exceptions vs. Errors ### Exceptions vs. Errors
@ -373,7 +373,7 @@ react to. They are generated at the syscall level: an exhaustive list of error
codes and their meanings is available by running `man 2 intro` or `man 3 errno` codes and their meanings is available by running `man 2 intro` or `man 3 errno`
on most Unices; or [online][]. on most Unices; or [online][].
In Node.js, system errors are represented as augmented Error objects -- not full In Node.js, system errors are represented as augmented `Error` objects -- not full
subclasses, but instead an error instance with added members. subclasses, but instead an error instance with added members.
### Class: System Error ### Class: System Error
@ -400,7 +400,7 @@ permissions.
#### EADDRINUSE: Address already in use #### EADDRINUSE: Address already in use
An attempt to bind a server ([net][], [http][], or [https][]) to a local An attempt to bind a server ([`net`][], [`http`][], or [`https`][]) to a local
address failed due to another server on the local system already occupying address failed due to another server on the local system already occupying
that address. that address.
@ -414,7 +414,7 @@ on the foreign host.
A connection was forcibly closed by a peer. This normally results A connection was forcibly closed by a peer. This normally results
from a loss of the connection on the remote socket due to a timeout from a loss of the connection on the remote socket due to a timeout
or reboot. Commonly encountered via the [http][] and [net][] modules. or reboot. Commonly encountered via the [`http`][] and [`net`][] modules.
#### EEXIST: File exists #### EEXIST: File exists
@ -438,18 +438,18 @@ that will run the Node.js process.
#### ENOENT: No such file or directory #### ENOENT: No such file or directory
Commonly raised by [fs][] operations; a component of the specified pathname Commonly raised by [`fs`][] operations; a component of the specified pathname
does not exist -- no entity (file or directory) could be found by the given path. does not exist -- no entity (file or directory) could be found by the given path.
#### ENOTDIR: Not a directory #### ENOTDIR: Not a directory
A component of the given pathname existed, but was not a directory as expected. A component of the given pathname existed, but was not a directory as expected.
Commonly raised by [fs.readdir][]. Commonly raised by [`fs.readdir`][].
#### ENOTEMPTY: Directory not empty #### ENOTEMPTY: Directory not empty
A directory with entries was the target of an operation that requires A directory with entries was the target of an operation that requires
an empty directory -- usually [fs.unlink][]. an empty directory -- usually [`fs.unlink`][].
#### EPERM: Operation not permitted #### EPERM: Operation not permitted
@ -459,30 +459,32 @@ privileges.
#### EPIPE: Broken pipe #### EPIPE: Broken pipe
A write on a pipe, socket, or FIFO for which there is no process to read the A write on a pipe, socket, or FIFO for which there is no process to read the
data. Commonly encountered at the [net][] and [http][] layers, indicative that data. Commonly encountered at the [`net`][] and [`http`][] layers, indicative that
the remote side of the stream being written to has been closed. the remote side of the stream being written to has been closed.
#### ETIMEDOUT: Operation timed out #### ETIMEDOUT: Operation timed out
A connect or send request failed because the connected party did not properly A connect or send request failed because the connected party did not properly
respond after a period of time. Usually encountered by [http][] or [net][] -- respond after a period of time. Usually encountered by [`http`][] or [`net`][] --
often a sign that a connected socket was not `.end()`'d appropriately. often a sign that a connected socket was not `.end()`'d appropriately.
[Error]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error [`Error`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
[`fs.readdir`]: fs.html#fs_fs_readdir_path_callback
[`fs.readFileSync`]: fs.html#fs_fs_readfilesync_file_options
[`fs.unlink`]: fs.html#fs_fs_unlink_path_callback
[`fs`]: fs.html
[`http`]: http.html
[`https`]: https.html
[`net`]: net.html
[`process.on('uncaughtException')`]: process.html#process_event_uncaughtexception
[`try / catch` construct]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
[`try { } catch(err) { }`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
[below]: #errors_error_propagation_and_interception [below]: #errors_error_propagation_and_interception
[fs.readFileSync]: fs.html#fs_fs_readfilesync_file_options
[stream-based]: stream.html
[event emitter-based]: events.html#events_class_events_eventemitter
[domains]: domain.html [domains]: domain.html
[process.on('uncaughtException')]: process.html#process_event_uncaughtexception [event emitter-based]: events.html#events_class_events_eventemitter
[V8's stack trace API]: https://code.google.com/p/v8-wiki/wiki/JavaScriptStackTraceApi [file descriptors]: http://en.wikipedia.org/wiki/File_descriptor
[vm]: vm.html
[online]: http://man7.org/linux/man-pages/man3/errno.3.html [online]: http://man7.org/linux/man-pages/man3/errno.3.html
[stream-based]: stream.html
[syscall]: http://man7.org/linux/man-pages/man2/syscall.2.html [syscall]: http://man7.org/linux/man-pages/man2/syscall.2.html
[net]: net.html [V8's stack trace API]: https://code.google.com/p/v8-wiki/wiki/JavaScriptStackTraceApi
[http]: http.html [vm]: vm.html
[https]: https.html
[file descriptors]: http://en.wikipedia.org/wiki/File_descriptor
[fs]: fs.html
[fs.readdir]: fs.html#fs_fs_readdir_path_callback
[fs.unlink]: fs.html#fs_fs_unlink_path_callback

117
doc/api/fs.markdown

@ -64,7 +64,7 @@ will be relative to `process.cwd()`.
Most fs functions let you omit the callback argument. If you do, a default Most fs functions let you omit the callback argument. If you do, a default
callback is used that rethrows errors. To get a trace to the original call callback is used that rethrows errors. To get a trace to the original call
site, set the NODE_DEBUG environment variable: site, set the `NODE_DEBUG` environment variable:
$ cat script.js $ cat script.js
function bad() { function bad() {
@ -94,7 +94,7 @@ Objects returned from `fs.watch()` are of this type.
* `filename` {String} The filename that changed (if relevant/available) * `filename` {String} The filename that changed (if relevant/available)
Emitted when something changes in a watched directory or file. Emitted when something changes in a watched directory or file.
See more details in [fs.watch][]. See more details in [`fs.watch()`][].
### Event: 'error' ### Event: 'error'
@ -118,18 +118,18 @@ Emitted when the ReadStream's file is opened.
## Class: fs.Stats ## Class: fs.Stats
Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their Objects returned from [`fs.stat()`][], [`fs.lstat()`][] and [`fs.fstat()`][] and their
synchronous counterparts are of this type. synchronous counterparts are of this type.
- `stats.isFile()` - `stats.isFile()`
- `stats.isDirectory()` - `stats.isDirectory()`
- `stats.isBlockDevice()` - `stats.isBlockDevice()`
- `stats.isCharacterDevice()` - `stats.isCharacterDevice()`
- `stats.isSymbolicLink()` (only valid with `fs.lstat()`) - `stats.isSymbolicLink()` (only valid with [`fs.lstat()`][])
- `stats.isFIFO()` - `stats.isFIFO()`
- `stats.isSocket()` - `stats.isSocket()`
For a regular file `util.inspect(stats)` would return a string very For a regular file [`util.inspect(stats)`][] would return a string very
similar to this: similar to this:
{ dev: 2114, { dev: 2114,
@ -148,9 +148,9 @@ similar to this:
birthtime: Mon, 10 Oct 2011 23:24:11 GMT } birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
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 to compare the values of
these objects you should use appropriate methods. For most general these objects you should use appropriate methods. For most general
uses [getTime()][MDN-Date-getTime] will return the number of uses [`getTime()`][MDN-Date-getTime] will return the number of
milliseconds elapsed since _1 January 1970 00:00:00 UTC_ and this milliseconds elapsed since _1 January 1970 00:00:00 UTC_ and this
integer should be sufficient for any comparison, however there are integer should be sufficient for any comparison, however there are
additional methods which can be used for displaying fuzzy information. additional methods which can be used for displaying fuzzy information.
@ -222,7 +222,7 @@ argument will be populated. The following example checks if the file
## fs.accessSync(path[, mode]) ## fs.accessSync(path[, mode])
Synchronous version of `fs.access`. This throws if any accessibility checks Synchronous version of [`fs.access()`][]. This throws if any accessibility checks
fail, and does nothing otherwise. fail, and does nothing otherwise.
## fs.appendFile(file, data[, options], callback) ## fs.appendFile(file, data[, options], callback)
@ -255,7 +255,7 @@ _Note: Specified file descriptors will not be closed automatically._
## fs.appendFileSync(file, data[, options]) ## fs.appendFileSync(file, data[, options])
The synchronous version of `fs.appendFile`. Returns `undefined`. The synchronous version of [`fs.appendFile()`][]. Returns `undefined`.
## fs.chmod(path, mode, callback) ## fs.chmod(path, mode, callback)
@ -286,7 +286,7 @@ Synchronous close(2). Returns `undefined`.
## fs.createReadStream(path[, options]) ## fs.createReadStream(path[, options])
Returns a new ReadStream object (See `Readable Stream`). Returns a new [`ReadStream`][] object. (See [Readable Stream][]).
Be aware that, unlike the default value set for `highWaterMark` on a Be aware that, unlike the default value set for `highWaterMark` on a
readable stream (16 kb), the stream returned by this method has a readable stream (16 kb), the stream returned by this method has a
@ -303,12 +303,12 @@ default value of 64 kb for the same parameter.
`options` can include `start` and `end` values to read a range of bytes from `options` can include `start` and `end` values to read a range of bytes from
the file instead of the entire file. Both `start` and `end` are inclusive and the file instead of the entire file. Both `start` and `end` are inclusive and
start at 0. The `encoding` can be any one of those accepted by [Buffer][]. start at 0. The `encoding` can be any one of those accepted by [`Buffer`][].
If `fd` is specified, `ReadStream` will ignore the `path` argument and will use If `fd` is specified, `ReadStream` will ignore the `path` argument and will use
the specified file descriptor. This means that no `open` event will be emitted. the specified file descriptor. This means that no `'open'` event will be emitted.
Note that `fd` should be blocking; non-blocking `fd`s should be passed to Note that `fd` should be blocking; non-blocking `fd`s should be passed to
`net.Socket`. [`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 your responsibility to close it and make sure
@ -327,7 +327,7 @@ If `options` is a string, then it specifies the encoding.
## fs.createWriteStream(path[, options]) ## fs.createWriteStream(path[, options])
Returns a new WriteStream object (See `Writable Stream`). Returns a new [`WriteStream`][] object. (See [Writable Stream][]).
`options` is an object or string with the following defaults: `options` is an object or string with the following defaults:
@ -339,18 +339,18 @@ Returns a new WriteStream object (See `Writable Stream`).
`options` may also include a `start` option to allow writing data at `options` may also include a `start` option to allow writing data at
some position past the beginning of the file. Modifying a file rather some position past the beginning of the file. Modifying a file rather
than replacing it may require a `flags` mode of `r+` rather than the than replacing it may require a `flags` mode of `r+` rather than the
default mode `w`. The `defaultEncoding` can be any one of those accepted by [Buffer][]. default mode `w`. The `defaultEncoding` can be any one of those accepted by [`Buffer`][].
Like `ReadStream` above, 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
`open` event will be emitted. Note that `fd` should be blocking; non-blocking `'open'` event will be emitted. Note that `fd` should be blocking; non-blocking
`fd`s should be passed to `net.Socket`. `fd`s should be passed to [`net.Socket`][].
If `options` is a string, then it specifies the encoding. If `options` is a string, then it specifies the encoding.
## fs.exists(path, callback) ## fs.exists(path, callback)
Stability: 0 - Deprecated: Use [fs.stat][] or [fs.access][] instead. Stability: 0 - Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.
Test whether or not the given path exists by checking with the file system. Test whether or not the given path exists by checking with the file system.
Then call the `callback` argument with either true or false. Example: Then call the `callback` argument with either true or false. Example:
@ -367,9 +367,9 @@ non-existent.
## fs.existsSync(path) ## fs.existsSync(path)
Stability: 0 - Deprecated: Use [fs.statSync][] or [fs.accessSync][] instead. Stability: 0 - Deprecated: Use [`fs.statSync()`][] or [`fs.accessSync()`][] instead.
Synchronous version of [`fs.exists`][]. Synchronous version of [`fs.exists()`][].
Returns `true` if the file exists, `false` otherwise. Returns `true` if the file exists, `false` otherwise.
## fs.fchmod(fd, mode, callback) ## fs.fchmod(fd, mode, callback)
@ -393,7 +393,7 @@ Synchronous fchown(2). Returns `undefined`.
## fs.fstat(fd, callback) ## fs.fstat(fd, callback)
Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where
`stats` is a `fs.Stats` object. `fstat()` is identical to `stat()`, except that `stats` is a `fs.Stats` object. `fstat()` is identical to [`stat()`][], except that
the file to be stat-ed is specified by the file descriptor `fd`. the file to be stat-ed is specified by the file descriptor `fd`.
## fs.fstatSync(fd) ## fs.fstatSync(fd)
@ -425,7 +425,7 @@ descriptor.
## fs.futimesSync(fd, atime, mtime) ## fs.futimesSync(fd, atime, mtime)
Synchronous version of `fs.futimes()`. Returns `undefined`. Synchronous version of [`fs.futimes()`][]. Returns `undefined`.
## fs.lchmod(path, mode, callback) ## fs.lchmod(path, mode, callback)
@ -540,7 +540,7 @@ the end of the file.
## fs.openSync(path, flags[, mode]) ## fs.openSync(path, flags[, mode])
Synchronous version of `fs.open()`. Returns an integer representing the file Synchronous version of [`fs.open()`][]. Returns an integer representing the file
descriptor. descriptor.
## fs.read(fd, buffer, offset, length, position, callback) ## fs.read(fd, buffer, offset, length, position, callback)
@ -599,7 +599,7 @@ _Note: Specified file descriptors will not be closed automatically._
## fs.readFileSync(file[, options]) ## fs.readFileSync(file[, options])
Synchronous version of `fs.readFile`. Returns the contents of the `file`. Synchronous version of [`fs.readFile`][]. Returns the contents of the `file`.
If the `encoding` option is specified then this function returns a If the `encoding` option is specified then this function returns a
string. Otherwise it returns a buffer. string. Otherwise it returns a buffer.
@ -630,7 +630,7 @@ Example:
## fs.readSync(fd, buffer, offset, length, position) ## fs.readSync(fd, buffer, offset, length, position)
Synchronous version of `fs.read`. Returns the number of `bytesRead`. Synchronous version of [`fs.read()`][]. Returns the number of `bytesRead`.
## fs.realpathSync(path[, cache]) ## fs.realpathSync(path[, cache])
@ -657,12 +657,12 @@ Synchronous rmdir(2). Returns `undefined`.
## fs.stat(path, callback) ## fs.stat(path, callback)
Asynchronous stat(2). The callback gets two arguments `(err, stats)` where Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
`stats` is a [fs.Stats][] object. See the [fs.Stats][] section below for more `stats` is a [`fs.Stats`][] object. See the [`fs.Stats`][] section below for more
information. information.
## fs.statSync(path) ## fs.statSync(path)
Synchronous stat(2). Returns an instance of `fs.Stats`. Synchronous stat(2). Returns an instance of [`fs.Stats`][].
## fs.symlink(destination, path[, type], callback) ## fs.symlink(destination, path[, type], callback)
@ -705,8 +705,8 @@ have effectively stopped watching `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.
_Note: `fs.watch` is more efficient than `fs.watchFile` and `fs.unwatchFile`. _Note: [`fs.watch()`][] is more efficient than `fs.watchFile()` and `fs.unwatchFile()`.
`fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()`
when possible._ when possible._
## fs.utimes(path, atime, mtime, callback) ## fs.utimes(path, atime, mtime, callback)
@ -716,19 +716,19 @@ Change file timestamps of the file referenced by the supplied path.
Note: the arguments `atime` and `mtime` of the following related functions does Note: the arguments `atime` and `mtime` of the following related functions does
follow the below rules: follow the below rules:
- If the value is a numberable string like "123456789", the value would get - If the value is a numberable string like `'123456789'`, the value would get
converted to corresponding number. converted to corresponding number.
- If the value is `NaN` or `Infinity`, the value would get converted to - If the value is `NaN` or `Infinity`, the value would get converted to
`Date.now()`. `Date.now()`.
## fs.utimesSync(path, atime, mtime) ## fs.utimesSync(path, atime, mtime)
Synchronous version of `fs.utimes()`. Returns `undefined`. Synchronous version of [`fs.utimes()`][]. Returns `undefined`.
## fs.watch(filename[, options][, listener]) ## fs.watch(filename[, options][, listener])
Watch for changes on `filename`, where `filename` is either a file or a Watch for changes on `filename`, where `filename` is either a file or a
directory. The returned object is a [fs.FSWatcher][]. directory. The returned object is a [`fs.FSWatcher`][].
The second argument is optional. The `options` if provided should be an object. The second argument is optional. The `options` if provided should be an object.
The supported boolean members are `persistent` and `recursive`. `persistent` The supported boolean members are `persistent` and `recursive`. `persistent`
@ -740,7 +740,7 @@ on supported platforms (See Caveats below).
The default is `{ persistent: true, recursive: false }`. The default is `{ persistent: true, recursive: false }`.
The listener callback gets two arguments `(event, filename)`. `event` is either The listener callback gets two arguments `(event, filename)`. `event` is either
'rename' or 'change', and `filename` is the name of the file which triggered `'rename'` or `'change'`, and `filename` is the name of the file which triggered
the event. the event.
### Caveats ### Caveats
@ -822,7 +822,7 @@ _Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will
of zero. If the file is created later on, the listener will be called again, of zero. If the file is created later on, the listener will be called again,
with the latest stat objects. This is a change in functionality since v0.10._ with the latest stat objects. This is a change in functionality since v0.10._
_Note: `fs.watch` is more efficient than `fs.watchFile` and `fs.unwatchFile`. _Note: [`fs.watch()`][] is more efficient than `fs.watchFile` and `fs.unwatchFile`.
`fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile`
when possible._ when possible._
@ -860,7 +860,7 @@ the current position. See pwrite(2).
The callback will receive the arguments `(err, written, string)` where `written` The callback will receive the arguments `(err, written, string)` where `written`
specifies how many _bytes_ the passed string required to be written. Note that specifies how many _bytes_ the passed string required to be written. Note that
bytes written is not the same as string characters. See [Buffer.byteLength][]. bytes written is not the same as string characters. See [`Buffer.byteLength`][].
Unlike when writing `buffer`, the entire string must be written. No substring Unlike when writing `buffer`, the entire string must be written. No substring
may be specified. This is because the byte offset of the resulting data may not may be specified. This is because the byte offset of the resulting data may not
@ -911,25 +911,40 @@ _Note: Specified file descriptors will not be closed automatically._
## fs.writeFileSync(file, data[, options]) ## fs.writeFileSync(file, data[, options])
The synchronous version of `fs.writeFile`. Returns `undefined`. The synchronous version of [`fs.writeFile()`][]. Returns `undefined`.
## fs.writeSync(fd, buffer, offset, length[, position]) ## fs.writeSync(fd, buffer, offset, length[, position])
## fs.writeSync(fd, data[, position[, encoding]]) ## fs.writeSync(fd, data[, position[, encoding]])
Synchronous versions of `fs.write()`. Returns the number of bytes written. Synchronous versions of [`fs.write()`][]. Returns the number of bytes written.
[fs.watch]: #fs_fs_watch_filename_options_listener [`Buffer.byteLength`]: buffer.html#buffer_class_method_buffer_bytelength_string_encoding
[Readable Stream]: stream.html#stream_class_stream_readable [`Buffer`]: buffer.html#buffer_buffer
[MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date [`fs.access()`]: #fs_fs_access_path_mode_callback
[`fs.accessSync()`]: #fs_fs_accesssync_path_mode
[`fs.appendFile()`]: fs.html#fs_fs_appendfile_file_data_options_callback
[`fs.exists()`]: fs.html#fs_fs_exists_path_callback
[`fs.fstat()`]: #fs_fs_fstat_fd_callback
[`fs.FSWatcher`]: #fs_class_fs_fswatcher
[`fs.futimes()`]: #fs_fs_futimes_fd_atime_mtime_callback
[`fs.lstat()`]: #fs_fs_lstat_path_callback
[`fs.open()`]: #fs_fs_open_path_flags_mode_callback
[`fs.read()`]: #fs_fs_read_fd_buffer_offset_length_position_callback
[`fs.readFile`]: #fs_fs_readfile_file_options_callback
[`fs.stat()`]: #fs_fs_stat_path_callback
[`fs.Stats`]: #fs_class_fs_stats
[`fs.statSync()`]: #fs_fs_statsync_path
[`fs.utimes()`]: #fs_fs_futimes_fd_atime_mtime_callback
[`fs.watch()`]: #fs_fs_watch_filename_options_listener
[`fs.write()`]: #fs_fs_write_fd_buffer_offset_length_position_callback
[`fs.writeFile()`]: #fs_fs_writefile_file_data_options_callback
[`net.Socket`]: net.html#net_class_net_socket
[`ReadStream`]: #fs_class_fs_readstream
[`stat()`]: fs.html#fs_fs_stat_path_callback
[`util.inspect(stats)`]: util.html#util_util_inspect_object_options
[`WriteStream`]: #fs_class_fs_writestream
[MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime [MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime
[MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
[Readable Stream]: stream.html#stream_class_stream_readable
[Writable Stream]: stream.html#stream_class_stream_writable [Writable Stream]: stream.html#stream_class_stream_writable
[fs.stat]: #fs_fs_stat_path_callback
[`fs.exists`]: fs.html#fs_fs_exists_path_callback
[fs.access]: #fs_fs_access_path_mode_callback
[fs.statSync]: #fs_fs_statsync_path
[fs.accessSync]: #fs_fs_accesssync_path_mode
[fs.Stats]: #fs_class_fs_stats
[Buffer]: buffer.html#buffer_buffer
[fs.FSWatcher]: #fs_class_fs_fswatcher
[Buffer.byteLength]: buffer.html#buffer_class_method_buffer_bytelength_string_encoding

16
doc/api/globals.markdown

@ -11,7 +11,7 @@ actually in the global scope but in the module scope - this will be noted.
* {Function} * {Function}
Used to handle binary data. See the [buffer section][] Used to handle binary data. See the [buffer section][].
## __dirname ## __dirname
@ -48,7 +48,7 @@ Example: running `node example.js` from `/Users/mjr`
## clearInterval(t) ## clearInterval(t)
Stop a timer that was previously created with `setInterval()`. The callback Stop a timer that was previously created with [`setInterval()`][]. The callback
will not execute. will not execute.
<!--type=global--> <!--type=global-->
@ -57,7 +57,7 @@ The timer functions are global variables. See the [timers][] section.
## clearTimeout(t) ## clearTimeout(t)
Stop a timer that was previously created with `setTimeout()`. The callback will Stop a timer that was previously created with [`setTimeout()`][]. The callback will
not execute. not execute.
## console ## console
@ -66,7 +66,7 @@ not execute.
* {Object} * {Object}
Used to print to stdout and stderr. See the [console][] section. Used to print to stdout and stderr. See the [`console`][] section.
## exports ## exports
@ -111,7 +111,7 @@ See the [module system documentation][] for more information.
* {Object} * {Object}
The process object. See the [process object][] section. The process object. See the [`process` object][] section.
## require() ## require()
@ -179,9 +179,11 @@ cannot span more than 24.8 days.
Returns an opaque value that represents the timer. Returns an opaque value that represents the timer.
[`console`]: console.html
[`process` object]: process.html#process_process
[`setInterval()`]: #globals_setinterval_cb_ms
[`setTimeout()`]: #globals_settimeout_cb_ms
[buffer section]: buffer.html [buffer section]: buffer.html
[module system documentation]: modules.html [module system documentation]: modules.html
[Modules]: modules.html#modules_modules [Modules]: modules.html#modules_modules
[process object]: process.html#process_process
[console]: console.html
[timers]: timers.html [timers]: timers.html

200
doc/api/http.markdown

@ -25,7 +25,7 @@ HTTP API is very low-level. It deals with stream handling and message
parsing only. It parses a message into headers and body but it does not parsing only. It parses a message into headers and body but it does not
parse the actual headers or the body. parse the actual headers or the body.
See [message.headers][] for details on how duplicate headers are handled. See [`message.headers`][] for details on how duplicate headers are handled.
The raw headers as they were received are retained in the `rawHeaders` The raw headers as they were received are retained in the `rawHeaders`
property, which is an array of `[key, value, key2, value2, ...]`. For property, which is an array of `[key, value, key2, value2, ...]`. For
@ -60,7 +60,7 @@ agents when they are no longer in use, so that the Sockets will be shut
down. down.
Sockets are removed from the agent's pool when the socket emits either Sockets are removed from the agent's pool when the socket emits either
a "close" event or a special "agentRemove" event. This means that if a `'close'` event or a special `'agentRemove'` event. This means that if
you intend to keep one HTTP request open for a long time and don't you intend to keep one HTTP request open for a long time and don't
want it to stay in the pool you can do something along the lines of: want it to stay in the pool you can do something along the lines of:
@ -97,10 +97,10 @@ Alternatively, you could just opt out of pooling entirely using
in a free state. Only relevant if `keepAlive` is set to `true`. in a free state. Only relevant if `keepAlive` is set to `true`.
Default = `256`. Default = `256`.
The default `http.globalAgent` that is used by `http.request` has all The default [`http.globalAgent`][] that is used by [`http.request()`][] has all
of these values set to their respective defaults. of these values set to their respective defaults.
To configure any of them, you must create your own `Agent` object. To configure any of them, you must create your own [`http.Agent`][] object.
```javascript ```javascript
var http = require('http'); var http = require('http');
@ -156,7 +156,7 @@ Agent. Do not modify.
## Class: http.ClientRequest ## Class: http.ClientRequest
This object is created internally and returned from `http.request()`. It This object is created internally and returned from [`http.request()`][]. It
represents an _in-progress_ request whose header has already been queued. The represents an _in-progress_ request whose header has already been queued. The
header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, header is still mutable using the `setHeader(name, value)`, `getHeader(name)`,
`removeHeader(name)` API. The actual header will be sent along with the first `removeHeader(name)` API. The actual header will be sent along with the first
@ -165,7 +165,7 @@ data chunk or when closing the connection.
To get the response, add a listener for `'response'` to the request object. To get the response, add a listener for `'response'` to the request object.
`'response'` will be emitted from the request object when the response `'response'` will be emitted from the request object when the response
headers have been received. The `'response'` event is executed with one headers have been received. The `'response'` event is executed with one
argument which is an instance of [http.IncomingMessage][]. argument which is an instance of [`http.IncomingMessage`][].
During the `'response'` event, one can add listeners to the During the `'response'` event, one can add listeners to the
response object; particularly to listen for the `'data'` event. response object; particularly to listen for the `'data'` event.
@ -183,7 +183,7 @@ Note: Node.js does not check whether Content-Length and the length of the body
which has been transmitted are equal or not. which has been transmitted are equal or not.
The request implements the [Writable Stream][] interface. This is an The request implements the [Writable Stream][] interface. This is an
[EventEmitter][] with the following events: [`EventEmitter`][] with the following events:
### Event: 'abort' ### Event: 'abort'
@ -196,11 +196,11 @@ emitted on the first call to `abort()`.
`function (response, socket, head) { }` `function (response, socket, head) { }`
Emitted each time a server responds to a request with a CONNECT method. If this Emitted each time a server responds to a request with a `CONNECT` method. If this
event isn't being listened for, clients receiving a CONNECT method will have event isn't being listened for, clients receiving a `CONNECT` method will have
their connections closed. their connections closed.
A client server pair that show you how to listen for the `connect` event. A client server pair that show you how to listen for the `'connect'` event.
var http = require('http'); var http = require('http');
var net = require('net'); var net = require('net');
@ -268,7 +268,7 @@ the client should send the request body.
`function (response) { }` `function (response) { }`
Emitted when a response is received to this request. This event is emitted only Emitted when a response is received to this request. This event is emitted only
once. The `response` argument will be an instance of [http.IncomingMessage][]. once. The `response` argument will be an instance of [`http.IncomingMessage`][].
Options: Options:
@ -290,7 +290,7 @@ Emitted each time a server responds to a request with an upgrade. If this
event isn't being listened for, clients receiving an upgrade header will have event isn't being listened for, clients receiving an upgrade header will have
their connections closed. their connections closed.
A client server pair that show you how to listen for the `upgrade` event. A client server pair that show you how to listen for the `'upgrade'` event.
var http = require('http'); var http = require('http');
@ -343,7 +343,7 @@ unsent, it will flush them to the stream. If the request is
chunked, this will send the terminating `'0\r\n\r\n'`. chunked, this will send the terminating `'0\r\n\r\n'`.
If `data` is specified, it is equivalent to calling If `data` is specified, it is equivalent to calling
`request.write(data, encoding)` followed by `request.end(callback)`. [`response.write(data, encoding)`][] followed by `request.end(callback)`.
If `callback` is specified, it will be called when the request stream If `callback` is specified, it will be called when the request stream
is finished. is finished.
@ -363,17 +363,17 @@ the optimization and kickstart the request.
### request.setNoDelay([noDelay]) ### request.setNoDelay([noDelay])
Once a socket is assigned to this request and is connected Once a socket is assigned to this request and is connected
[socket.setNoDelay()][] will be called. [`socket.setNoDelay()`][] will be called.
### request.setSocketKeepAlive([enable][, initialDelay]) ### request.setSocketKeepAlive([enable][, initialDelay])
Once a socket is assigned to this request and is connected Once a socket is assigned to this request and is connected
[socket.setKeepAlive()][] will be called. [`socket.setKeepAlive()`][] will be called.
### request.setTimeout(timeout[, callback]) ### request.setTimeout(timeout[, callback])
Once a socket is assigned to this request and is connected Once a socket is assigned to this request and is connected
[socket.setTimeout()][] will be called. [`socket.setTimeout()`][] will be called.
### request.write(chunk[, encoding][, callback]) ### request.write(chunk[, encoding][, callback])
@ -383,7 +383,7 @@ server--in that case it is suggested to use the
`['Transfer-Encoding', 'chunked']` header line when `['Transfer-Encoding', 'chunked']` header line when
creating the request. creating the request.
The `chunk` argument should be a [Buffer][] or a string. The `chunk` argument should be a [`Buffer`][] or a string.
The `encoding` argument is optional and only applies when `chunk` is a string. The `encoding` argument is optional and only applies when `chunk` is a string.
Defaults to `'utf8'`. Defaults to `'utf8'`.
@ -395,7 +395,7 @@ Returns `request`.
## Class: http.Server ## Class: http.Server
This is an [EventEmitter][] with the following events: This is an [`EventEmitter`][] with the following events:
### Event: 'checkContinue' ### Event: 'checkContinue'
@ -405,21 +405,21 @@ Emitted each time a request with an http Expect: 100-continue is received.
If this event isn't listened for, the server will automatically respond If this event isn't listened for, the server will automatically respond
with a 100 Continue as appropriate. with a 100 Continue as appropriate.
Handling this event involves calling [response.writeContinue()][] if the client Handling this event involves calling [`response.writeContinue()`][] if the client
should continue to send the request body, or generating an appropriate HTTP should continue to send the request body, or generating an appropriate HTTP
response (e.g., 400 Bad Request) if the client should not continue to send the response (e.g., 400 Bad Request) if the client should not continue to send the
request body. request body.
Note that when this event is emitted and handled, the `request` event will Note that when this event is emitted and handled, the `'request'` event will
not be emitted. not be emitted.
### Event: 'clientError' ### Event: 'clientError'
`function (exception, socket) { }` `function (exception, socket) { }`
If a client connection emits an 'error' event, it will be forwarded here. If a client connection emits an `'error'` event, it will be forwarded here.
`socket` is the `net.Socket` object that the error originated from. `socket` is the [`net.Socket`][] object that the error originated from.
### Event: 'close' ### Event: 'close'
@ -431,8 +431,8 @@ Emitted when the server closes.
`function (request, socket, head) { }` `function (request, socket, head) { }`
Emitted each time a client requests a http CONNECT method. If this event isn't Emitted each time a client requests a http `CONNECT` method. If this event isn't
listened for, then clients requesting a CONNECT method will have their listened for, then clients requesting a `CONNECT` method will have their
connections closed. connections closed.
* `request` is the arguments for the http request, as it is in the request * `request` is the arguments for the http request, as it is in the request
@ -441,7 +441,7 @@ connections closed.
* `head` is an instance of Buffer, the first packet of the tunneling stream, * `head` is an instance of Buffer, the first packet of the tunneling stream,
this may be empty. this may be empty.
After this event is emitted, the request's socket will not have a `data` After this event is emitted, the request's socket will not have a `'data'`
event listener, meaning you will need to bind to it in order to handle data event listener, meaning you will need to bind to it in order to handle data
sent to the server on that socket. sent to the server on that socket.
@ -450,8 +450,8 @@ sent to the server on that socket.
`function (socket) { }` `function (socket) { }`
When a new TCP stream is established. `socket` is an object of type When a new TCP stream is established. `socket` is an object of type
`net.Socket`. Usually users will not want to access this event. In [`net.Socket`][]. Usually users will not want to access this event. In
particular, the socket will not emit `readable` events because of how particular, the socket will not emit `'readable'` events because of how
the protocol parser attaches to the socket. The `socket` can also be the protocol parser attaches to the socket. The `socket` can also be
accessed at `request.connection`. accessed at `request.connection`.
@ -461,8 +461,8 @@ accessed at `request.connection`.
Emitted each time there is a request. Note that there may be multiple requests Emitted each time there is a request. Note that there may be multiple requests
per connection (in the case of keep-alive connections). per connection (in the case of keep-alive connections).
`request` is an instance of [http.IncomingMessage][] and `response` is `request` is an instance of [`http.IncomingMessage`][] and `response` is
an instance of [http.ServerResponse][]. an instance of [`http.ServerResponse`][].
### Event: 'upgrade' ### Event: 'upgrade'
@ -478,13 +478,13 @@ closed.
* `head` is an instance of Buffer, the first packet of the upgraded stream, * `head` is an instance of Buffer, the first packet of the upgraded stream,
this may be empty. this may be empty.
After this event is emitted, the request's socket will not have a `data` After this event is emitted, the request's socket will not have a `'data'`
event listener, meaning you will need to bind to it in order to handle data event listener, meaning you will need to bind to it in order to handle data
sent to the server on that socket. sent to the server on that socket.
### server.close([callback]) ### server.close([callback])
Stops the server from accepting new connections. See [net.Server.close()][]. Stops the server from accepting new connections. See [`net.Server.close()`][].
### server.listen(handle[, callback]) ### server.listen(handle[, callback])
@ -501,14 +501,14 @@ already been bound to a port or domain socket.
Listening on a file descriptor is not supported on Windows. Listening on a file descriptor is not supported on Windows.
This function is asynchronous. The last parameter `callback` will be added as This function is asynchronous. The last parameter `callback` will be added as
a listener for the ['listening'][] event. See also [net.Server.listen()][]. a listener for the `'listening'` event. See also [`net.Server.listen()`][].
### server.listen(path[, callback]) ### server.listen(path[, callback])
Start a UNIX socket server listening for connections on the given `path`. Start a UNIX socket server listening for connections on the given `path`.
This function is asynchronous. The last parameter `callback` will be added as This function is asynchronous. The last parameter `callback` will be added as
a listener for the ['listening'][] event. See also [net.Server.listen(path)][]. a listener for the `'listening'` event. See also [`net.Server.listen(path)`][].
### server.listen(port[, hostname][, backlog][, callback]) ### server.listen(port[, hostname][, backlog][, callback])
@ -525,7 +525,7 @@ The actual length will be determined by your OS through sysctl settings such as
parameter is 511 (not 512). parameter is 511 (not 512).
This function is asynchronous. The last parameter `callback` will be added as This function is asynchronous. The last parameter `callback` will be added as
a listener for the ['listening'][] event. See also [net.Server.listen(port)][]. a listener for the `'listening'` event. See also [`net.Server.listen(port)`][].
### server.maxHeadersCount ### server.maxHeadersCount
@ -571,14 +571,14 @@ This object is created internally by a HTTP server--not by the user. It is
passed as the second parameter to the `'request'` event. passed as the second parameter to the `'request'` event.
The response implements the [Writable Stream][] interface. This is an The response implements the [Writable Stream][] interface. This is an
[EventEmitter][] with the following events: [`EventEmitter`][] with the following events:
### Event: 'close' ### Event: 'close'
`function () { }` `function () { }`
Indicates that the underlying connection was terminated before Indicates that the underlying connection was terminated before
[response.end()][] was called or able to flush. [`response.end()`][] was called or able to flush.
### Event: 'finish' ### Event: 'finish'
@ -610,17 +610,16 @@ emit trailers, with a list of the header fields in its value. E.g.,
response.end(); response.end();
Attempting to set a trailer field name that contains invalid characters will Attempting to set a trailer field name that contains invalid characters will
result in a `TypeError` being thrown. result in a [`TypeError`][] being thrown.
### response.end([data][, encoding][, callback]) ### response.end([data][, encoding][, callback])
This method signals to the server that all of the response headers and body This method signals to the server that all of the response headers and body
have been sent; that server should consider this message complete. have been sent; that server should consider this message complete.
The method, `response.end()`, MUST be called on each The method, `response.end()`, MUST be called on each response.
response.
If `data` is specified, it is equivalent to calling If `data` is specified, it is equivalent to calling
`response.write(data, encoding)` followed by `response.end(callback)`. [`response.write(data, encoding)`][] followed by `response.end(callback)`.
If `callback` is specified, it will be called when the response stream If `callback` is specified, it will be called when the response stream
is finished. is finished.
@ -628,7 +627,7 @@ is finished.
### response.finished ### response.finished
Boolean value that indicates whether the response has completed. Starts Boolean value that indicates whether the response has completed. Starts
as `false`. After `response.end()` executes, the value will be `true`. as `false`. After [`response.end()`][] executes, the value will be `true`.
### response.getHeader(name) ### response.getHeader(name)
@ -675,7 +674,7 @@ or
response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]); response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
Attempting to set a header field name that contains invalid characters will Attempting to set a header field name that contains invalid characters will
result in a `TypeError` being thrown. result in a [`TypeError`][] being thrown.
### response.setTimeout(msecs, callback) ### response.setTimeout(msecs, callback)
@ -696,7 +695,7 @@ Returns `response`.
### response.statusCode ### response.statusCode
When using implicit headers (not calling [response.writeHead()][] explicitly), When using implicit headers (not calling [`response.writeHead()`][] explicitly),
this property controls the status code that will be sent to the client when this property controls the status code that will be sent to the client when
the headers get flushed. the headers get flushed.
@ -709,7 +708,7 @@ status code which was sent out.
### response.statusMessage ### response.statusMessage
When using implicit headers (not calling `response.writeHead()` explicitly), this property When using implicit headers (not calling [`response.writeHead()`][] explicitly), this property
controls the status message that will be sent to the client when the headers get controls the status message that will be sent to the client when the headers get
flushed. If this is left as `undefined` then the standard message for the status flushed. If this is left as `undefined` then the standard message for the status
code will be used. code will be used.
@ -723,7 +722,7 @@ status message which was sent out.
### response.write(chunk[, encoding][, callback]) ### response.write(chunk[, encoding][, callback])
If this method is called and [response.writeHead()][] has not been called, If this method is called and [`response.writeHead()`][] has not been called,
it will switch to implicit header mode and flush the implicit headers. it will switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method may This sends a chunk of the response body. This method may
@ -737,9 +736,9 @@ will be called when this chunk of data is flushed.
**Note**: This is the raw HTTP body and has nothing to do with **Note**: This is the raw HTTP body and has nothing to do with
higher-level multi-part body encodings that may be used. higher-level multi-part body encodings that may be used.
The first time `response.write()` is called, it will send the buffered The first time [`response.write()`][] is called, it will send the buffered
header information and the first body to the client. The second time header information and the first body to the client. The second time
`response.write()` is called, Node.js assumes you're going to be streaming [`response.write()`][] is called, Node.js assumes you're going to be streaming
data, and sends that separately. That is, the response is buffered up to the data, and sends that separately. That is, the response is buffered up to the
first chunk of body. first chunk of body.
@ -750,7 +749,7 @@ buffer. Returns `false` if all or part of the data was queued in user memory.
### response.writeContinue() ### response.writeContinue()
Sends a HTTP/1.1 100 Continue message to the client, indicating that Sends a HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the ['checkContinue'][] event on `Server`. the request body should be sent. See the [`'checkContinue'`][] event on `Server`.
### response.writeHead(statusCode[, statusMessage][, headers]) ### response.writeHead(statusCode[, statusMessage][, headers])
@ -767,9 +766,9 @@ Example:
'Content-Type': 'text/plain' }); 'Content-Type': 'text/plain' });
This method must only be called once on a message and it must This method must only be called once on a message and it must
be called before [response.end()][] is called. be called before [`response.end()`][] is called.
If you call [response.write()][] or [response.end()][] before calling this, the If you call [`response.write()`][] or [`response.end()`][] before calling this, the
implicit/mutable headers will be calculated and call this function for you. implicit/mutable headers will be calculated and call this function for you.
Note that Content-Length is given in bytes not characters. The above example Note that Content-Length is given in bytes not characters. The above example
@ -781,8 +780,8 @@ which has been transmitted are equal or not.
## http.IncomingMessage ## http.IncomingMessage
An `IncomingMessage` object is created by [http.Server][] or An `IncomingMessage` object is created by [`http.Server`][] or
[http.ClientRequest][] and passed as the first argument to the `'request'` [`http.ClientRequest`][] and passed as the first argument to the `'request'`
and `'response'` event respectively. It may be used to access response status, and `'response'` event respectively. It may be used to access response status,
headers and data. headers and data.
@ -831,7 +830,7 @@ Also `response.httpVersionMajor` is the first integer and
### message.method ### message.method
**Only valid for request obtained from [http.Server][].** **Only valid for request obtained from [`http.Server`][].**
The request method as a string. Read only. Example: The request method as a string. Read only. Example:
`'GET'`, `'DELETE'`. `'GET'`, `'DELETE'`.
@ -861,7 +860,7 @@ Header names are not lowercased, and duplicates are not merged.
### message.rawTrailers ### message.rawTrailers
The raw request/response trailer keys and values exactly as they were The raw request/response trailer keys and values exactly as they were
received. Only populated at the 'end' event. received. Only populated at the `'end'` event.
### message.setTimeout(msecs, callback) ### message.setTimeout(msecs, callback)
@ -874,30 +873,30 @@ Returns `message`.
### message.statusCode ### message.statusCode
**Only valid for response obtained from `http.ClientRequest`.** **Only valid for response obtained from [`http.ClientRequest`][].**
The 3-digit HTTP response status code. E.G. `404`. The 3-digit HTTP response status code. E.G. `404`.
### message.statusMessage ### message.statusMessage
**Only valid for response obtained from `http.ClientRequest`.** **Only valid for response obtained from [`http.ClientRequest`][].**
### message.socket ### message.socket
The `net.Socket` object associated with the connection. The [`net.Socket`][] object associated with the connection.
With HTTPS support, use [request.socket.getPeerCertificate()][] to obtain the With HTTPS support, use [`request.socket.getPeerCertificate()`][] to obtain the
client's authentication details. client's authentication details.
The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`.
### message.trailers ### message.trailers
The request/response trailers object. Only populated at the 'end' event. The request/response trailers object. Only populated at the `'end'` event.
### message.url ### message.url
**Only valid for request obtained from [http.Server][].** **Only valid for request obtained from [`http.Server`][].**
Request URL string. This contains only the URL that is Request URL string. This contains only the URL that is
present in the actual HTTP request. If the request is: present in the actual HTTP request. If the request is:
@ -945,14 +944,14 @@ Found'`.
## http.createClient([port][, host]) ## http.createClient([port][, host])
Stability: 0 - Deprecated: Use [http.request][] instead. Stability: 0 - Deprecated: Use [`http.request()`][] instead.
Constructs a new HTTP client. `port` and `host` refer to the server to be Constructs a new HTTP client. `port` and `host` refer to the server to be
connected to. connected to.
## http.createServer([requestListener]) ## http.createServer([requestListener])
Returns a new instance of [http.Server][]. Returns a new instance of [`http.Server`][].
The `requestListener` is a function which is automatically The `requestListener` is a function which is automatically
added to the `'request'` event. added to the `'request'` event.
@ -960,7 +959,7 @@ added to the `'request'` event.
## http.get(options[, callback]) ## http.get(options[, callback])
Since most requests are GET requests without bodies, Node.js provides this Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and `http.request()` convenience method. The only difference between this method and [`http.request()`][]
is that it sets the method to GET and calls `req.end()` automatically. is that it sets the method to GET and calls `req.end()` automatically.
Example: Example:
@ -982,14 +981,14 @@ Node.js maintains several connections per server to make HTTP requests.
This function allows one to transparently issue requests. This function allows one to transparently issue requests.
`options` can be an object or a string. If `options` is a string, it is `options` can be an object or a string. If `options` is a string, it is
automatically parsed with [url.parse()][]. automatically parsed with [`url.parse()`][].
Options: Options:
- `protocol`: Protocol to use. Defaults to `'http'`. - `protocol`: Protocol to use. Defaults to `'http'`.
- `host`: A domain name or IP address of the server to issue the request to. - `host`: A domain name or IP address of the server to issue the request to.
Defaults to `'localhost'`. Defaults to `'localhost'`.
- `hostname`: Alias for `host`. To support `url.parse()` `hostname` is - `hostname`: Alias for `host`. To support [`url.parse()`][] `hostname` is
preferred over `host`. preferred over `host`.
- `family`: IP address family to use when resolving `host` and `hostname`. - `family`: IP address family to use when resolving `host` and `hostname`.
Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be
@ -1005,17 +1004,17 @@ Options:
- `headers`: An object containing request headers. - `headers`: An object containing request headers.
- `auth`: Basic authentication i.e. `'user:password'` to compute an - `auth`: Basic authentication i.e. `'user:password'` to compute an
Authorization header. Authorization header.
- `agent`: Controls [Agent][] behavior. When an Agent is used request will - `agent`: Controls [`Agent`][] behavior. When an Agent is used request will
default to `Connection: keep-alive`. Possible values: default to `Connection: keep-alive`. Possible values:
- `undefined` (default): use [globalAgent][] for this host and port. - `undefined` (default): use [`http.globalAgent`][] for this host and port.
- `Agent` object: explicitly use the passed in `Agent`. - `Agent` object: explicitly use the passed in `Agent`.
- `false`: opts out of connection pooling with an Agent, defaults request to - `false`: opts out of connection pooling with an Agent, defaults request to
`Connection: close`. `Connection: close`.
The optional `callback` parameter will be added as a one time listener for The optional `callback` parameter will be added as a one time listener for
the ['response'][] event. the `'response'` event.
`http.request()` returns an instance of the [http.ClientRequest][] `http.request()` returns an instance of the [`http.ClientRequest`][]
class. The `ClientRequest` instance is a writable stream. If one needs to class. The `ClientRequest` instance is a writable stream. If one needs to
upload a file with a POST request, then write to the `ClientRequest` object. upload a file with a POST request, then write to the `ClientRequest` object.
@ -1073,41 +1072,44 @@ There are a few special headers that should be noted.
* Sending an 'Expect' header will immediately send the request headers. * Sending an 'Expect' header will immediately send the request headers.
Usually, when sending 'Expect: 100-continue', you should both set a timeout Usually, when sending 'Expect: 100-continue', you should both set a timeout
and listen for the `continue` event. See RFC2616 Section 8.2.3 for more and listen for the `'continue'` event. See RFC2616 Section 8.2.3 for more
information. information.
* Sending an Authorization header will override using the `auth` option * Sending an Authorization header will override using the `auth` option
to compute basic authentication. to compute basic authentication.
[message.headers][]: #http_message_headers [`'checkContinue'`]: #http_event_checkcontinue
[constructor options]: #http_new_agent_options [`'listening'`]: net.html#net_event_listening
[`'response'`]: #http_event_response
[`Agent`]: #http_class_http_agent
[`Buffer`]: buffer.html#buffer_buffer
[`destroy()`]: #http_agent_destroy [`destroy()`]: #http_agent_destroy
['checkContinue']: #http_event_checkcontinue [`EventEmitter`]: events.html#events_class_events_eventemitter
['listening']: net.html#net_event_listening [`http.Agent`]: #http_class_http_agent
['response']: #http_event_response [`http.ClientRequest`]: #http_class_http_clientrequest
[Agent]: #http_class_http_agent [`http.globalAgent`]: #http_http_globalagent
[Buffer]: buffer.html#buffer_buffer [`http.IncomingMessage`]: #http_http_incomingmessage
[EventEmitter]: events.html#events_class_events_eventemitter [`http.request()`]: #http_http_request_options_callback
[`http.Server`]: #http_class_http_server
[`http.ServerResponse`]: #http_class_http_serverresponse
[`message.headers`]: #http_message_headers
[`net.Server.close()`]: net.html#net_server_close_callback
[`net.Server.listen()`]: net.html#net_server_listen_handle_callback
[`net.Server.listen(path)`]: net.html#net_server_listen_path_callback
[`net.Server.listen(port)`]: net.html#net_server_listen_port_hostname_backlog_callback
[`net.Socket`]: net.html#net_class_net_socket
[`request.socket.getPeerCertificate()`]: tls.html#tls_tlssocket_getpeercertificate_detailed
[`response.end()`]: #http_response_end_data_encoding_callback
[`response.write()`]: #http_response_write_chunk_encoding_callback
[`response.write(data, encoding)`]: #http_response_write_chunk_encoding_callback
[`response.writeContinue()`]: #http_response_writecontinue
[`response.writeHead()`]: #http_response_writehead_statuscode_statusmessage_headers
[`socket.setKeepAlive()`]: net.html#net_socket_setkeepalive_enable_initialdelay
[`socket.setNoDelay()`]: net.html#net_socket_setnodelay_nodelay
[`socket.setTimeout()`]: net.html#net_socket_settimeout_timeout_callback
[`stream.setEncoding()`]: stream.html#stream_stream_setencoding_encoding
[`TypeError`]: errors.html#errors_class_typeerror
[`url.parse()`]: url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost
[constructor options]: #http_new_agent_options
[Readable Stream]: stream.html#stream_class_stream_readable [Readable Stream]: stream.html#stream_class_stream_readable
[Writable Stream]: stream.html#stream_class_stream_writable [Writable Stream]: stream.html#stream_class_stream_writable
[globalAgent]: #http_http_globalagent
[http.ClientRequest]: #http_class_http_clientrequest
[http.IncomingMessage]: #http_http_incomingmessage
[http.ServerResponse]: #http_class_http_serverresponse
[http.Server]: #http_class_http_server
[http.request]: #http_http_request_options_callback
[net.Server.close()]: net.html#net_server_close_callback
['listening']: net.html#net_event_listening
[net.Server.listen(path)]: net.html#net_server_listen_path_callback
[net.Server.listen(port)]: net.html#net_server_listen_port_hostname_backlog_callback
[net.Server.listen()]: net.html#net_server_listen_handle_callback
[response.end()]: #http_response_end_data_encoding_callback
[response.write()]: #http_response_write_chunk_encoding_callback
[response.writeContinue()]: #http_response_writecontinue
[response.writeHead()]: #http_response_writehead_statuscode_statusmessage_headers
[socket.setKeepAlive()]: net.html#net_socket_setkeepalive_enable_initialdelay
[socket.setNoDelay()]: net.html#net_socket_setnodelay_nodelay
[socket.setTimeout()]: net.html#net_socket_settimeout_timeout_callback
[request.socket.getPeerCertificate()]: tls.html#tls_tlssocket_getpeercertificate_detailed
[stream.setEncoding()]: stream.html#stream_stream_setencoding_encoding
[url.parse()]: url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost

66
doc/api/https.markdown

@ -7,26 +7,26 @@ separate module.
## Class: https.Agent ## Class: https.Agent
An Agent object for HTTPS similar to [http.Agent][]. See [https.request()][] An Agent object for HTTPS similar to [`http.Agent`][]. See [`https.request()`][]
for more information. for more information.
## Class: https.Server ## Class: https.Server
This class is a subclass of `tls.Server` and emits events same as This class is a subclass of `tls.Server` and emits events same as
`http.Server`. See `http.Server` for more information. [`http.Server`][]. See [`http.Server`][] for more information.
### server.setTimeout(msecs, callback) ### server.setTimeout(msecs, callback)
See [http.Server#setTimeout()][]. See [`http.Server#setTimeout()`][].
### server.timeout ### server.timeout
See [http.Server#timeout][]. See [`http.Server#timeout`][].
## https.createServer(options[, requestListener]) ## https.createServer(options[, requestListener])
Returns a new HTTPS web server object. The `options` is similar to Returns a new HTTPS web server object. The `options` is similar to
[tls.createServer()][]. The `requestListener` is a function which is [`tls.createServer()`][]. The `requestListener` is a function which is
automatically added to the `'request'` event. automatically added to the `'request'` event.
Example: Example:
@ -61,20 +61,20 @@ Or
### server.close([callback]) ### server.close([callback])
See [http.close()][] for details. See [`http.close()`][] for details.
### server.listen(handle[, callback]) ### server.listen(handle[, callback])
### server.listen(path[, callback]) ### server.listen(path[, callback])
### server.listen(port[, host][, backlog][, callback]) ### server.listen(port[, host][, backlog][, callback])
See [http.listen()][] for details. See [`http.listen()`][] for details.
## https.get(options, callback) ## https.get(options, callback)
Like `http.get()` but for HTTPS. Like [`http.get()`][] but for HTTPS.
`options` can be an object or a string. If `options` is a string, it is `options` can be an object or a string. If `options` is a string, it is
automatically parsed with [url.parse()][]. automatically parsed with [`url.parse()`][].
Example: Example:
@ -94,16 +94,16 @@ Example:
## https.globalAgent ## https.globalAgent
Global instance of [https.Agent][] for all HTTPS client requests. Global instance of [`https.Agent`][] for all HTTPS client requests.
## https.request(options, callback) ## https.request(options, callback)
Makes a request to a secure web server. Makes a request to a secure web server.
`options` can be an object or a string. If `options` is a string, it is `options` can be an object or a string. If `options` is a string, it is
automatically parsed with [url.parse()][]. automatically parsed with [`url.parse()`][].
All options from [http.request()][] are valid. All options from [`http.request()`][] are valid.
Example: Example:
@ -150,15 +150,15 @@ The options argument has the following options
- `headers`: An object containing request headers. - `headers`: An object containing request headers.
- `auth`: Basic authentication i.e. `'user:password'` to compute an - `auth`: Basic authentication i.e. `'user:password'` to compute an
Authorization header. Authorization header.
- `agent`: Controls [Agent][] behavior. When an Agent is used request will - `agent`: Controls [`Agent`][] behavior. When an Agent is used request will
default to `Connection: keep-alive`. Possible values: default to `Connection: keep-alive`. Possible values:
- `undefined` (default): use [globalAgent][] for this host and port. - `undefined` (default): use [`globalAgent`][] for this host and port.
- `Agent` object: explicitly use the passed in `Agent`. - `Agent` object: explicitly use the passed in `Agent`.
- `false`: opts out of connection pooling with an Agent, defaults request to - `false`: opts out of connection pooling with an Agent, defaults request to
`Connection: close`. `Connection: close`.
The following options from [tls.connect()][] can also be specified. However, a The following options from [`tls.connect()`][] can also be specified. However, a
[globalAgent][] silently ignores these. [`globalAgent`][] silently ignores these.
- `pfx`: Certificate, Private key and CA certificates to use for SSL. Default `null`. - `pfx`: Certificate, Private key and CA certificates to use for SSL. Default `null`.
- `key`: Private key to use for SSL. Default `null`. - `key`: Private key to use for SSL. Default `null`.
@ -175,9 +175,9 @@ The following options from [tls.connect()][] can also be specified. However, a
request is sent. Default `true`. request is sent. Default `true`.
- `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force - `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force
SSL version 3. The possible values depend on your installation of SSL version 3. The possible values depend on your installation of
OpenSSL and are defined in the constant [SSL_METHODS][]. OpenSSL and are defined in the constant [`SSL_METHODS`][].
In order to specify these options, use a custom `Agent`. In order to specify these options, use a custom [`Agent`][].
Example: Example:
@ -213,17 +213,19 @@ Example:
... ...
} }
[http.Server#setTimeout()]: http.html#http_server_settimeout_msecs_callback [`Agent`]: #https_class_https_agent
[http.Server#timeout]: http.html#http_server_timeout [`globalAgent`]: #https_https_globalagent
[Agent]: #https_class_https_agent [`http.Agent`]: http.html#http_class_http_agent
[globalAgent]: #https_https_globalagent [`http.close()`]: http.html#http_server_close_callback
[http.listen()]: http.html#http_server_listen_port_hostname_backlog_callback [`http.get()`]: http.html#http_http_get_options_callback
[url.parse()]: url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost [`http.listen()`]: http.html#http_server_listen_port_hostname_backlog_callback
[http.close()]: http.html#http_server_close_callback [`http.request()`]: http.html#http_http_request_options_callback
[http.Agent]: http.html#http_class_http_agent [`http.Server#setTimeout()`]: http.html#http_server_settimeout_msecs_callback
[http.request()]: http.html#http_http_request_options_callback [`http.Server#timeout`]: http.html#http_server_timeout
[https.Agent]: #https_class_https_agent [`http.Server`]: http.html#http_class_http_server
[https.request()]: #https_https_request_options_callback [`https.Agent`]: #https_class_https_agent
[tls.connect()]: tls.html#tls_tls_connect_options_callback [`https.request()`]: #https_https_request_options_callback
[tls.createServer()]: tls.html#tls_tls_createserver_options_secureconnectionlistener [`SSL_METHODS`]: http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS
[SSL_METHODS]: http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS [`tls.connect()`]: tls.html#tls_tls_connect_options_callback
[`tls.createServer()`]: tls.html#tls_tls_createserver_options_secureconnectionlistener
[`url.parse()`]: url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost

5
doc/api/modules.markdown

@ -299,7 +299,7 @@ A required module prefixed with `'./'` is relative to the file calling
Without a leading '/', './', or '../' to indicate a file, the module must Without a leading '/', './', or '../' to indicate a file, the module must
either be a core module or is loaded from a `node_modules` folder. either be a core module or is loaded from a `node_modules` folder.
If the given path does not exist, `require()` will throw an Error with its If the given path does not exist, `require()` will throw an [`Error`][] with its
`code` property set to `'MODULE_NOT_FOUND'`. `code` property set to `'MODULE_NOT_FOUND'`.
## Folders as Modules ## Folders as Modules
@ -519,4 +519,5 @@ 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.
[module resolution]: https://nodejs.org/api/modules.html#modules_all_together [`Error`]: errors.html#errors_class_error
[module resolution]: #modules_all_together

138
doc/api/net.markdown

@ -10,7 +10,7 @@ this module with `require('net');`.
This class is used to create a TCP or local server. This class is used to create a TCP or local server.
`net.Server` is an [EventEmitter][] with the following events: `net.Server` is an [`EventEmitter`][] with the following events:
### Event: 'close' ### Event: 'close'
@ -28,7 +28,7 @@ Emitted when a new connection is made. `socket` is an instance of
* {Error Object} * {Error Object}
Emitted when an error occurs. The ['close'][] event will be called directly Emitted when an error occurs. The [`'close'`][] event will be called directly
following this event. See example in discussion of `server.listen`. following this event. See example in discussion of `server.listen`.
### Event: 'listening' ### Event: 'listening'
@ -61,19 +61,19 @@ Don't call `server.address()` until the `'listening'` event has been emitted.
Stops the server from accepting new connections and keeps existing Stops the server from accepting new connections and keeps existing
connections. This function is asynchronous, the server is finally connections. This function is asynchronous, the server is finally
closed when all connections are ended and the server emits a ['close'][] event. closed when all connections are ended and the server emits a [`'close'`][] event.
The optional `callback` will be called once the `'close'` event occurs. Unlike The optional `callback` will be called once the `'close'` event occurs. Unlike
that event, it will be called with an Error as its only argument if the server that event, it will be called with an Error as its only argument if the server
was not open when it was closed. was not open when it was closed.
### server.connections ### server.connections
Stability: 0 - Deprecated: Use [server.getConnections][] instead. Stability: 0 - Deprecated: Use [`server.getConnections`][] instead.
The number of concurrent connections on the server. The number of concurrent connections on the server.
This becomes `null` when sending a socket to a child with This becomes `null` when sending a socket to a child with
`child_process.fork()`. To poll forks and get current number of active [`child_process.fork()`][]. To poll forks and get current number of active
connections use asynchronous `server.getConnections` instead. connections use asynchronous `server.getConnections` instead.
### server.getConnections(callback) ### server.getConnections(callback)
@ -98,9 +98,9 @@ already been bound to a port or domain socket.
Listening on a file descriptor is not supported on Windows. Listening on a file descriptor is not supported on Windows.
This function is asynchronous. When the server has been bound, This function is asynchronous. When the server has been bound,
['listening'][] event will be emitted. [`'listening'`][] event will be emitted.
The last parameter `callback` will be added as a listener for the The last parameter `callback` will be added as a listener for the
['listening'][] event. [`'listening'`][] event.
### server.listen(options[, callback]) ### server.listen(options[, callback])
@ -138,8 +138,8 @@ shown below.
Start a local socket server listening for connections on the given `path`. Start a local socket server listening for connections on the given `path`.
This function is asynchronous. When the server has been bound, This function is asynchronous. When the server has been bound,
['listening'][] event will be emitted. The last parameter `callback` [`'listening'`][] event will be emitted. The last parameter `callback`
will be added as a listener for the ['listening'][] event. will be added as a listener for the [`'listening'`][] event.
On UNIX, the local domain is usually known as the UNIX domain. The path is a On UNIX, the local domain is usually known as the UNIX domain. The path is a
filesystem path name. It is subject to the same naming conventions and filesystem path name. It is subject to the same naming conventions and
@ -170,8 +170,8 @@ The actual length will be determined by your OS through sysctl settings such as
parameter is 511 (not 512). parameter is 511 (not 512).
This function is asynchronous. When the server has been bound, This function is asynchronous. When the server has been bound,
['listening'][] event will be emitted. The last parameter `callback` [`'listening'`][] event will be emitted. The last parameter `callback`
will be added as a listener for the ['listening'][] event. will be added as a listener for the [`'listening'`][] event.
One issue some users run into is getting `EADDRINUSE` errors. This means that One issue some users run into is getting `EADDRINUSE` errors. This means that
another server is already running on the requested port. One way of handling this another server is already running on the requested port. One way of handling this
@ -195,7 +195,7 @@ Set this property to reject connections when the server's connection count gets
high. high.
It is not recommended to use this option once a socket has been sent to a child It is not recommended to use this option once a socket has been sent to a child
with `child_process.fork()`. with [`child_process.fork()`][].
### server.ref() ### server.ref()
@ -217,7 +217,7 @@ Returns `server`.
This object is an abstraction of a TCP or local socket. `net.Socket` This object is an abstraction of a TCP or local socket. `net.Socket`
instances implement a duplex Stream interface. They can be created by the instances implement a duplex Stream interface. They can be created by the
user and used as a client (with `connect()`) or they can be created by Node.js user and used as a client (with [`connect()`][]) or they can be created by Node.js
and passed to the user through the `'connection'` event of a server. and passed to the user through the `'connection'` event of a server.
### new net.Socket([options]) ### new net.Socket([options])
@ -237,7 +237,7 @@ Set `readable` and/or `writable` to `true` to allow reads and/or writes on this
socket (NOTE: Works only when `fd` is passed). socket (NOTE: Works only when `fd` is passed).
About `allowHalfOpen`, refer to `createServer()` and `'end'` event. About `allowHalfOpen`, refer to `createServer()` and `'end'` event.
`net.Socket` instances are [EventEmitter][] with the following events: `net.Socket` instances are [`EventEmitter`][] with the following events:
### Event: 'close' ### Event: 'close'
@ -249,7 +249,7 @@ which says if the socket was closed due to a transmission error.
### Event: 'connect' ### Event: 'connect'
Emitted when a socket connection is successfully established. Emitted when a socket connection is successfully established.
See `connect()`. See [`connect()`][].
### Event: 'data' ### Event: 'data'
@ -290,16 +290,16 @@ following this event.
Emitted after resolving the hostname but before connecting. Emitted after resolving the hostname but before connecting.
Not applicable to UNIX sockets. Not applicable to UNIX sockets.
* `err` {Error | Null} The error object. See [dns.lookup()][]. * `err` {Error | Null} The error object. See [`dns.lookup()`][].
* `address` {String} The IP address. * `address` {String} The IP address.
* `family` {String | Null} The address type. See [dns.lookup()][]. * `family` {String | Null} The address type. See [`dns.lookup()`][].
### Event: 'timeout' ### Event: 'timeout'
Emitted if the socket times out from inactivity. This is only to notify that Emitted if the socket times out from inactivity. This is only to notify that
the socket has been idle. The user must manually close the connection. the socket has been idle. The user must manually close the connection.
See also: `socket.setTimeout()` See also: [`socket.setTimeout()`][]
### socket.address() ### socket.address()
@ -324,7 +324,7 @@ written, but the buffer may contain strings, and the strings are lazily
encoded, so the exact number of bytes is not known.) encoded, so the exact number of bytes is not known.)
Users who experience large or growing `bufferSize` should attempt to Users who experience large or growing `bufferSize` should attempt to
"throttle" the data flows in their program with `pause()` and `resume()`. "throttle" the data flows in their program with [`pause()`][] and [`resume()`][].
### socket.bytesRead ### socket.bytesRead
@ -360,17 +360,17 @@ specifies:
Normally this method is not needed, as `net.createConnection` opens the Normally this method is not needed, as `net.createConnection` opens the
socket. Use this only if you are implementing a custom Socket. socket. Use this only if you are implementing a custom Socket.
This function is asynchronous. When the ['connect'][] event is emitted the This function is asynchronous. When the [`'connect'`][] event is emitted the
socket is established. If there is a problem connecting, the `'connect'` event socket is established. If there is a problem connecting, the `'connect'` event
will not be emitted, the `'error'` event will be emitted with the exception. will not be emitted, the [`'error'`][] event will be emitted with the exception.
The `connectListener` parameter will be added as a listener for the The `connectListener` parameter will be added as a listener for the
['connect'][] event. [`'connect'`][] event.
### socket.connect(path[, connectListener]) ### socket.connect(path[, connectListener])
### socket.connect(port[, host][, connectListener]) ### socket.connect(port[, host][, connectListener])
As [socket.connect(options[, connectListener])](#net_socket_connect_options_connectlistener), As [`socket.connect(options\[, connectListener\])`][],
with options either as either `{port: port, host: host}` or `{path: path}`. with options either as either `{port: port, host: host}` or `{path: path}`.
### socket.destroy() ### socket.destroy()
@ -399,7 +399,7 @@ The numeric representation of the local port. For example,
### socket.pause() ### socket.pause()
Pauses the reading of data. That is, `'data'` events will not be emitted. Pauses the reading of data. That is, [`'data'`][] events will not be emitted.
Useful to throttle back an upload. Useful to throttle back an upload.
### socket.ref() ### socket.ref()
@ -426,12 +426,12 @@ The numeric representation of the remote port. For example,
### socket.resume() ### socket.resume()
Resumes reading after a call to `pause()`. Resumes reading after a call to [`pause()`][].
### socket.setEncoding([encoding]) ### socket.setEncoding([encoding])
Set the encoding for the socket as a Readable Stream. See Set the encoding for the socket as a [Readable Stream][]. See
[stream.setEncoding()][] for more information. [`stream.setEncoding()`][] for more information.
### socket.setKeepAlive([enable][, initialDelay]) ### socket.setKeepAlive([enable][, initialDelay])
@ -460,14 +460,14 @@ Returns `socket`.
Sets the socket to timeout after `timeout` milliseconds of inactivity on Sets the socket to timeout after `timeout` milliseconds of inactivity on
the socket. By default `net.Socket` do not have a timeout. the socket. By default `net.Socket` do not have a timeout.
When an idle timeout is triggered the socket will receive a `'timeout'` When an idle timeout is triggered the socket will receive a [`'timeout'`][]
event but the connection will not be severed. The user must manually `end()` event but the connection will not be severed. The user must manually [`end()`][]
or `destroy()` the socket. or [`destroy()`][] the socket.
If `timeout` is 0, then the existing idle timeout is disabled. If `timeout` is 0, then the existing idle timeout is disabled.
The optional `callback` parameter will be added as a one time listener for the The optional `callback` parameter will be added as a one time listener for the
`'timeout'` event. [`'timeout'`][] event.
Returns `socket`. Returns `socket`.
@ -486,21 +486,21 @@ case of a string--it defaults to UTF8 encoding.
Returns `true` if the entire data was flushed successfully to the kernel Returns `true` if the entire data was flushed successfully to the kernel
buffer. Returns `false` if all or part of the data was queued in user memory. buffer. Returns `false` if all or part of the data was queued in user memory.
`'drain'` will be emitted when the buffer is again free. [`'drain'`][] will be emitted when the buffer is again free.
The optional `callback` parameter will be executed when the data is finally The optional `callback` parameter will be executed when the data is finally
written out - this may not be immediately. written out - this may not be immediately.
## net.connect(options[, connectListener]) ## net.connect(options[, connectListener])
A factory function, which returns a new ['net.Socket'][] and automatically A factory function, which returns a new [`net.Socket`][] and automatically
connects with the supplied `options`. connects with the supplied `options`.
The options are passed to both the ['net.Socket'][] constructor and the The options are passed to both the [`net.Socket`][] constructor and the
['socket.connect'][] method. [`socket.connect`][] method.
The `connectListener` parameter will be added as a listener for the The `connectListener` parameter will be added as a listener for the
['connect'][] event once. [`'connect'`][] event once.
Here is an example of a client of the previously described echo server: Here is an example of a client of the previously described echo server:
@ -525,32 +525,32 @@ changed to
## net.connect(path[, connectListener]) ## net.connect(path[, connectListener])
A factory function, which returns a new unix ['net.Socket'][] and automatically A factory function, which returns a new unix [`net.Socket`][] and automatically
connects to the supplied `path`. connects to the supplied `path`.
The `connectListener` parameter will be added as a listener for the The `connectListener` parameter will be added as a listener for the
['connect'][] event once. [`'connect'`][] event once.
## net.connect(port[, host][, connectListener]) ## net.connect(port[, host][, connectListener])
A factory function, which returns a new ['net.Socket'][] and automatically A factory function, which returns a new [`net.Socket`][] and automatically
connects to the supplied `port` and `host`. connects to the supplied `port` and `host`.
If `host` is omitted, `'localhost'` will be assumed. If `host` is omitted, `'localhost'` will be assumed.
The `connectListener` parameter will be added as a listener for the The `connectListener` parameter will be added as a listener for the
['connect'][] event once. [`'connect'`][] event once.
## net.createConnection(options[, connectListener]) ## net.createConnection(options[, connectListener])
A factory function, which returns a new ['net.Socket'][] and automatically A factory function, which returns a new [`net.Socket`][] and automatically
connects with the supplied `options`. connects with the supplied `options`.
The options are passed to both the ['net.Socket'][] constructor and the The options are passed to both the [`net.Socket`][] constructor and the
['socket.connect'][] method. [`socket.connect`][] method.
The `connectListener` parameter will be added as a listener for the The `connectListener` parameter will be added as a listener for the
['connect'][] event once. [`'connect'`][] event once.
Here is an example of a client of the previously described echo server: Here is an example of a client of the previously described echo server:
@ -575,26 +575,26 @@ changed to
## net.createConnection(path[, connectListener]) ## net.createConnection(path[, connectListener])
A factory function, which returns a new unix ['net.Socket'][] and automatically A factory function, which returns a new unix [`net.Socket`][] and automatically
connects to the supplied `path`. connects to the supplied `path`.
The `connectListener` parameter will be added as a listener for the The `connectListener` parameter will be added as a listener for the
['connect'][] event once. [`'connect'`][] event once.
## net.createConnection(port[, host][, connectListener]) ## net.createConnection(port[, host][, connectListener])
A factory function, which returns a new ['net.Socket'][] and automatically A factory function, which returns a new [`net.Socket`][] and automatically
connects to the supplied `port` and `host`. connects to the supplied `port` and `host`.
If `host` is omitted, `'localhost'` will be assumed. If `host` is omitted, `'localhost'` will be assumed.
The `connectListener` parameter will be added as a listener for the The `connectListener` parameter will be added as a listener for the
['connect'][] event once. [`'connect'`][] event once.
## net.createServer([options][, connectionListener]) ## net.createServer([options][, connectionListener])
Creates a new server. The `connectionListener` argument is Creates a new server. The `connectionListener` argument is
automatically set as a listener for the ['connection'][] event. automatically set as a listener for the [`'connection'`][] event.
`options` is an object with the following defaults: `options` is an object with the following defaults:
@ -605,13 +605,13 @@ automatically set as a listener for the ['connection'][] event.
If `allowHalfOpen` is `true`, then the socket won't automatically send a FIN If `allowHalfOpen` is `true`, then the socket won't automatically send a FIN
packet when the other end of the socket sends a FIN packet. The socket becomes packet when the other end of the socket sends a FIN packet. The socket becomes
non-readable, but still writable. You should call the `end()` method explicitly. non-readable, but still writable. You should call the [`end()`][] method explicitly.
See ['end'][] event for more information. See [`'end'`][] event for more information.
If `pauseOnConnect` is `true`, then the socket associated with each incoming If `pauseOnConnect` is `true`, then the socket associated with each incoming
connection will be paused, and no data will be read from its handle. This allows connection will be paused, and no data will be read from its handle. This allows
connections to be passed between processes without any data being read by the connections to be passed between processes without any data being read by the
original process. To begin reading data from a paused socket, call `resume()`. original process. To begin reading data from a paused socket, call [`resume()`][].
Here is an example of an echo server which listens for connections Here is an example of an echo server which listens for connections
on port 8124: on port 8124:
@ -657,15 +657,27 @@ Returns true if input is a version 4 IP address, otherwise returns false.
Returns true if input is a version 6 IP address, otherwise returns false. Returns true if input is a version 6 IP address, otherwise returns false.
['close']: #net_event_close [`'close'`]: #net_event_close
['connect']: #net_event_connect [`'connect'`]: #net_event_connect
['connection']: #net_event_connection [`'connection'`]: #net_event_connection
['end']: #net_event_end [`'data'`]: #net_event_data
[EventEmitter]: events.html#events_class_events_eventemitter [`'drain'`]: #net_event_drain
['listening']: #net_event_listening [`'end'`]: #net_event_end
[server.getConnections]: #net_server_getconnections_callback [`'error'`]: #net_event_error_1
[`'listening'`]: #net_event_listening
[`'timeout'`]: #net_event_timeout
[`child_process.fork()`]: child_process.html#child_process_child_process_fork_modulepath_args_options
[`connect()`]: #net_socket_connect_options_connectlistener
[`destroy()`]: #net_socket_destroy
[`dns.lookup()`]: dns.html#dns_dns_lookup_hostname_options_callback
[`end()`]: #net_socket_end_data_encoding
[`EventEmitter`]: events.html#events_class_events_eventemitter
[`net.Socket`]: #net_class_net_socket
[`pause()`]: #net_socket_pause
[`resume()`]: #net_socket_resume
[`server.getConnections`]: #net_server_getconnections_callback
[`socket.connect(options\[, connectListener\])`]: #net_socket_connect_options_connectlistener
[`socket.connect`]: #net_socket_connect_options_connectlistener
[`socket.setTimeout()`]: #net_socket_settimeout_timeout_callback
[`stream.setEncoding()`]: stream.html#stream_readable_setencoding_encoding
[Readable Stream]: stream.html#stream_class_stream_readable [Readable Stream]: stream.html#stream_class_stream_readable
[stream.setEncoding()]: stream.html#stream_readable_setencoding_encoding
['net.Socket']: #net_class_net_socket
[dns.lookup()]: dns.html#dns_dns_lookup_hostname_options_callback
['socket.connect']: #net_socket_connect_options_connectlistener

80
doc/api/process.markdown

@ -3,22 +3,22 @@
<!-- type=global --> <!-- type=global -->
The `process` object is a global object and can be accessed from anywhere. The `process` object is a global object and can be accessed from anywhere.
It is an instance of [EventEmitter][]. It is an instance of [`EventEmitter`][].
## Event: 'beforeExit' ## Event: 'beforeExit'
This event is emitted when Node.js empties its event loop and has nothing else to This event is emitted when Node.js empties its event loop and has nothing else to
schedule. Normally, Node.js exits when there is no work scheduled, but a listener schedule. Normally, Node.js exits when there is no work scheduled, but a listener
for 'beforeExit' can make asynchronous calls, and cause Node.js to continue. for `'beforeExit'` can make asynchronous calls, and cause Node.js to continue.
'beforeExit' is not emitted for conditions causing explicit termination, such as `'beforeExit'` is not emitted for conditions causing explicit termination, such as
`process.exit()` or uncaught exceptions, and should not be used as an [`process.exit()`][] or uncaught exceptions, and should not be used as an
alternative to the 'exit' event unless the intention is to schedule more work. alternative to the `'exit'` event unless the intention is to schedule more work.
## Event: 'exit' ## Event: 'exit'
Emitted when the process is about to exit. There is no way to prevent the Emitted when the process is about to exit. There is no way to prevent the
exiting of the event loop at this point, and once all `exit` listeners have exiting of the event loop at this point, and once all `'exit'` listeners have
finished running the process will exit. Therefore you **must** only perform finished running the process will exit. Therefore you **must** only perform
**synchronous** operations in this handler. This is a good hook to perform **synchronous** operations in this handler. This is a good hook to perform
checks on the module's state (like for unit tests). The callback takes one checks on the module's state (like for unit tests). The callback takes one
@ -27,7 +27,7 @@ argument, the code the process is exiting with.
This event is only emitted when Node.js exits explicitly by process.exit() or This event is only emitted when Node.js exits explicitly by process.exit() or
implicitly by the event loop draining. implicitly by the event loop draining.
Example of listening for `exit`: Example of listening for `'exit'`:
process.on('exit', function(code) { process.on('exit', function(code) {
// do *NOT* do this // do *NOT* do this
@ -40,10 +40,10 @@ Example of listening for `exit`:
## Event: 'message' ## Event: 'message'
* `message` {Object} a parsed JSON object or primitive value * `message` {Object} a parsed JSON object or primitive value
* `sendHandle` {Handle object} a [net.Socket][] or [net.Server][] object, or * `sendHandle` {Handle object} a [`net.Socket`][] or [`net.Server`][] object, or
undefined. undefined.
Messages sent by [ChildProcess.send()][] are obtained using the `'message'` Messages sent by [`ChildProcess.send()`][] are obtained using the `'message'`
event on the child's process object. event on the child's process object.
## Event: 'rejectionHandled' ## Event: 'rejectionHandled'
@ -63,9 +63,9 @@ event loop turn it takes for the `'unhandledRejection'` event to be emitted.
Another way of stating this is that, unlike in synchronous code where there is Another way of stating this is that, unlike in synchronous code where there is
an ever-growing list of unhandled exceptions, with promises there is a an ever-growing list of unhandled exceptions, with promises there is a
growing-and-shrinking list of unhandled rejections. In synchronous code, the growing-and-shrinking list of unhandled rejections. In synchronous code, the
'uncaughtException' event tells you when the list of unhandled exceptions `'uncaughtException'` event tells you when the list of unhandled exceptions
grows. And in asynchronous code, the `'unhandledRejection'` event tells you grows. And in asynchronous code, the `'unhandledRejection'` event tells you
when the list of unhandled rejections grows, while the 'rejectionHandled' when the list of unhandled rejections grows, while the `'rejectionHandled'`
event tells you when the list of unhandled rejections shrinks. event tells you when the list of unhandled rejections shrinks.
For example using the rejection detection hooks in order to keep a map of all For example using the rejection detection hooks in order to keep a map of all
@ -91,7 +91,7 @@ Emitted when an exception bubbles all the way back to the event loop. If a
listener is added for this exception, the default action (which is to print listener is added for this exception, the default action (which is to print
a stack trace and exit) will not occur. a stack trace and exit) will not occur.
Example of listening for `uncaughtException`: Example of listening for `'uncaughtException'`:
process.on('uncaughtException', function(err) { process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err); console.log('Caught exception: ' + err);
@ -105,7 +105,7 @@ Example of listening for `uncaughtException`:
nonexistentFunc(); nonexistentFunc();
console.log('This will not run.'); console.log('This will not run.');
Note that `uncaughtException` is a very crude mechanism for exception Note that `'uncaughtException'` is a very crude mechanism for exception
handling. handling.
Do *not* use it as the Node.js equivalent of `On Error Resume Next`. An Do *not* use it as the Node.js equivalent of `On Error Resume Next`. An
@ -115,9 +115,9 @@ is in an undefined state. Blindly resuming means *anything* could happen.
Think of resuming as pulling the power cord when you are upgrading your system. Think of resuming as pulling the power cord when you are upgrading your system.
Nine out of ten times nothing happens - but the 10th time, your system is bust. Nine out of ten times nothing happens - but the 10th time, your system is bust.
`uncaughtException` should be used to perform synchronous cleanup before `'uncaughtException'` should be used to perform synchronous cleanup before
shutting down the process. It is not safe to resume normal operation after shutting down the process. It is not safe to resume normal operation after
`uncaughtException`. If you do use it, restart your application after every `'uncaughtException'`. If you do use it, restart your application after every
unhandled exception! unhandled exception!
You have been warned. You have been warned.
@ -127,12 +127,12 @@ You have been warned.
Emitted whenever a `Promise` is rejected and no error handler is attached to Emitted whenever a `Promise` is rejected and no error handler is attached to
the promise within a turn of the event loop. When programming with promises the promise within a turn of the event loop. When programming with promises
exceptions are encapsulated as rejected promises. Such promises can be caught exceptions are encapsulated as rejected promises. Such promises can be caught
and handled using `promise.catch(...)` and rejections are propagated through and handled using [`promise.catch(...)`][] and rejections are propagated through
a promise chain. This event is useful for detecting and keeping track of a promise chain. This event is useful for detecting and keeping track of
promises that were rejected whose rejections were not handled yet. This event promises that were rejected whose rejections were not handled yet. This event
is emitted with the following arguments: is emitted with the following arguments:
- `reason` the object with which the promise was rejected (usually an `Error` - `reason` the object with which the promise was rejected (usually an [`Error`][]
instance). instance).
- `p` the promise that was rejected. - `p` the promise that was rejected.
@ -175,7 +175,7 @@ operations are pending. The following status codes are used in other
cases: cases:
* `1` **Uncaught Fatal Exception** - There was an uncaught exception, * `1` **Uncaught Fatal Exception** - There was an uncaught exception,
and it was not handled by a domain or an `uncaughtException` event and it was not handled by a domain or an `'uncaughtException'` event
handler. handler.
* `2` - Unused (reserved by Bash for builtin misuse) * `2` - Unused (reserved by Bash for builtin misuse)
* `3` **Internal JavaScript Parse Error** - The JavaScript source code * `3` **Internal JavaScript Parse Error** - The JavaScript source code
@ -219,7 +219,7 @@ cases:
<!--name=SIGINT, SIGHUP, etc.--> <!--name=SIGINT, SIGHUP, etc.-->
Emitted when the processes receives a signal. See sigaction(2) for a list of Emitted when the processes receives a signal. See sigaction(2) for a list of
standard POSIX signal names such as SIGINT, SIGHUP, etc. standard POSIX signal names such as `SIGINT`, `SIGHUP`, etc.
Example of listening for `SIGINT`: Example of listening for `SIGINT`:
@ -315,7 +315,7 @@ Changes the current working directory of the process or throws an exception if t
An Object containing the JavaScript representation of the configure options An Object containing the JavaScript representation of the configure options
that were used to compile the current Node.js executable. This is the same as that were used to compile the current Node.js executable. This is the same as
the "config.gypi" file that was produced when running the `./configure` script. the `config.gypi` file that was produced when running the `./configure` script.
An example of the possible output looks like: An example of the possible output looks like:
@ -357,7 +357,7 @@ Returns the current working directory of the process.
Close the IPC channel to the parent process, allowing this child to exit Close the IPC channel to the parent process, allowing this child to exit
gracefully once there are no other connections keeping it alive. gracefully once there are no other connections keeping it alive.
Identical to the parent process's [ChildProcess.disconnect()][]. Identical to the parent process's [`ChildProcess.disconnect()`][].
If Node.js was not spawned with an IPC channel, `process.disconnect()` will be If Node.js was not spawned with an IPC channel, `process.disconnect()` will be
undefined. undefined.
@ -434,7 +434,7 @@ The shell that executed Node.js should see the exit code as 1.
## process.exitCode ## process.exitCode
A number which will be the process exit code, when the process either A number which will be the process exit code, when the process either
exits gracefully, or is exited via `process.exit()` without specifying exits gracefully, or is exited via [`process.exit()`][] without specifying
a code. a code.
Specifying a code to `process.exit(code)` will override any previous Specifying a code to `process.exit(code)` will override any previous
@ -527,7 +527,7 @@ Android)
Reads /etc/group and initializes the group access list, using all groups of Reads /etc/group and initializes the group access list, using all groups of
which the user is a member. This is a privileged operation, meaning you need which the user is a member. This is a privileged operation, meaning you need
to be root or have the CAP_SETGID capability. to be root or have the `CAP_SETGID` capability.
`user` is a user name or user ID. `extra_group` is a group name or group ID. `user` is a user name or user ID. `extra_group` is a group name or group ID.
@ -543,7 +543,7 @@ Some care needs to be taken when dropping privileges. Example:
Send a signal to a process. `pid` is the process id and `signal` is the Send a signal to a process. `pid` is the process id and `signal` is the
string describing the signal to send. Signal names are strings like string describing the signal to send. Signal names are strings like
'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'. `SIGINT` or `SIGHUP`. If omitted, the signal will be `SIGTERM`.
See [Signal Events][] and kill(2) for more information. See [Signal Events][] and kill(2) for more information.
Will throw an error if target does not exist, and as a special case, a signal Will throw an error if target does not exist, and as a special case, a signal
@ -604,7 +604,7 @@ This will generate:
Once the current event loop turn runs to completion, call the callback Once the current event loop turn runs to completion, call the callback
function. function.
This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more This is *not* a simple alias to [`setTimeout(fn, 0)`][], it's much more
efficient. It runs before any additional I/O events (including efficient. It runs before any additional I/O events (including
timers) fire in subsequent ticks of the event loop. timers) fire in subsequent ticks of the event loop.
@ -693,8 +693,8 @@ for the source tarball and headers-only tarball.
`process.release` contains the following properties: `process.release` contains the following properties:
* `name`: a string with a value that will always be `"node"` for Node.js. For * `name`: a string with a value that will always be `'node'` for Node.js. For
legacy io.js releases, this will be `"io.js"`. legacy io.js releases, this will be `'io.js'`.
* `sourceUrl`: a complete URL pointing to a _.tar.gz_ file containing the * `sourceUrl`: a complete URL pointing to a _.tar.gz_ file containing the
source of the current release. source of the current release.
* `headersUrl`: a complete URL pointing to a _.tar.gz_ file containing only * `headersUrl`: a complete URL pointing to a _.tar.gz_ file containing only
@ -724,7 +724,7 @@ relied upon to exist.
When Node.js is spawned with an IPC channel attached, it can send messages to its When Node.js is spawned with an IPC channel attached, it can send messages to its
parent process using `process.send()`. Each will be received as a parent process using `process.send()`. Each will be received as a
['message'][] event on the parent's `ChildProcess` object. [`'message'`][] event on the parent's `ChildProcess` object.
If Node.js was not spawned with an IPC channel, `process.send()` will be undefined. If Node.js was not spawned with an IPC channel, `process.send()` will be undefined.
@ -794,7 +794,7 @@ Note: this function is only available on POSIX platforms (i.e. not Windows,
Android) Android)
Sets the supplementary group IDs. This is a privileged operation, meaning you Sets the supplementary group IDs. This is a privileged operation, meaning you
need to be root or have the CAP_SETGID capability. need to be root or have the `CAP_SETGID` capability.
The list can contain group IDs, group names or both. The list can contain group IDs, group names or both.
@ -869,7 +869,7 @@ For example, a `console.log` equivalent could look like this:
}; };
`process.stderr` and `process.stdout` are unlike other streams in Node.js in `process.stderr` and `process.stdout` are unlike other streams in Node.js in
that they cannot be closed (`end()` will throw), they never emit the `finish` that they cannot be closed (`end()` will throw), they never emit the `'finish'`
event and that writes can block when output is redirected to a file (although event and that writes can block when output is redirected to a file (although
disks are fast and operating systems normally employ write-back caching so it disks are fast and operating systems normally employ write-back caching so it
should be a very rare occurrence indeed.) should be a very rare occurrence indeed.)
@ -891,7 +891,7 @@ See [the tty docs][] for more information.
## process.title ## process.title
Getter/setter to set what is displayed in 'ps'. Getter/setter to set what is displayed in `ps.
When used as a setter, the maximum length is platform-specific and probably When used as a setter, the maximum length is platform-specific and probably
short. short.
@ -944,13 +944,17 @@ Will print something like:
icu: '55.1', icu: '55.1',
openssl: '1.0.1k' } openssl: '1.0.1k' }
[ChildProcess.disconnect()]: child_process.html#child_process_child_disconnect [`'message'`]: child_process.html#child_process_event_message
[ChildProcess.send()]: child_process.html#child_process_child_send_message_sendhandle_callback [`ChildProcess.disconnect()`]: child_process.html#child_process_child_disconnect
[Signal Events]: #process_signal_events [`ChildProcess.send()`]: child_process.html#child_process_child_send_message_sendhandle_callback
[EventEmitter]: events.html#events_class_events_eventemitter [`Error`]: errors.html#errors_class_error
[net.Server]: net.html#net_class_net_server [`EventEmitter`]: events.html#events_class_events_eventemitter
[net.Socket]: net.html#net_class_net_socket [`net.Server`]: net.html#net_class_net_server
[`net.Socket`]: net.html#net_class_net_socket
[`process.exit()`]: #process_process_exit_code
[`promise.catch(...)`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
[`require.main`]: modules.html#modules_accessing_the_main_module [`require.main`]: modules.html#modules_accessing_the_main_module
['message']: child_process.html#child_process_event_message [`setTimeout(fn, 0)`]: timers.html#timers_settimeout_callback_delay_arg
[Signal Events]: #process_signal_events
[Stream compatibility]: stream.html#stream_compatibility_with_older_node_js_versions [Stream compatibility]: stream.html#stream_compatibility_with_older_node_js_versions
[the tty docs]: tty.html#tty_tty [the tty docs]: tty.html#tty_tty

34
doc/api/readline.markdown

@ -3,7 +3,7 @@
Stability: 2 - Stable Stability: 2 - Stable
To use this module, do `require('readline')`. Readline allows reading of a To use this module, do `require('readline')`. Readline allows reading of a
stream (such as `process.stdin`) on a line-by-line basis. stream (such as [`process.stdin`][]) on a line-by-line basis.
Note that once you've invoked this module, your Node.js program will not Note that once you've invoked this module, your Node.js program will not
terminate until you've closed the interface. Here's how to allow your terminate until you've closed the interface. Here's how to allow your
@ -31,13 +31,14 @@ stream.
### rl.close() ### rl.close()
Closes the `Interface` instance, relinquishing control on the `input` and Closes the `Interface` instance, relinquishing control on the `input` and
`output` streams. The "close" event will also be emitted. `output` streams. The `'close'` event will also be emitted.
### rl.pause() ### rl.pause()
Pauses the readline `input` stream, allowing it to be resumed later if needed. Pauses the readline `input` stream, allowing it to be resumed later if needed.
Note that this doesn't immediately pause the stream of events. Several events may be emitted after calling `pause`, including `line`. Note that this doesn't immediately pause the stream of events. Several events may
be emitted after calling `pause`, including `line`.
### rl.prompt([preserveCursor]) ### rl.prompt([preserveCursor])
@ -100,7 +101,7 @@ Example:
Emitted when `close()` is called. Emitted when `close()` is called.
Also emitted when the `input` stream receives its "end" event. The `Interface` Also emitted when the `input` stream receives its `'end'` event. The `Interface`
instance should be considered "finished" once this is emitted. For example, when instance should be considered "finished" once this is emitted. For example, when
the `input` stream receives `^D`, respectively known as `EOT`. the `input` stream receives `^D`, respectively known as `EOT`.
@ -114,7 +115,7 @@ the `input` stream receives a `^C`, respectively known as `SIGINT`.
Emitted whenever the `input` stream receives a `\n`, usually received when the Emitted whenever the `input` stream receives a `\n`, usually received when the
user hits enter, or return. This is a good hook to listen for user input. user hits enter, or return. This is a good hook to listen for user input.
Example of listening for `line`: Example of listening for `'line'`:
rl.on('line', function (cmd) { rl.on('line', function (cmd) {
console.log('You just typed: '+cmd); console.log('You just typed: '+cmd);
@ -129,7 +130,7 @@ Emitted whenever the `input` stream is paused.
Also emitted whenever the `input` stream is not paused and receives the Also emitted whenever the `input` stream is not paused and receives the
`SIGCONT` event. (See events `SIGTSTP` and `SIGCONT`) `SIGCONT` event. (See events `SIGTSTP` and `SIGCONT`)
Example of listening for `pause`: Example of listening for `'pause'`:
rl.on('pause', function() { rl.on('pause', function() {
console.log('Readline paused.'); console.log('Readline paused.');
@ -141,7 +142,7 @@ Example of listening for `pause`:
Emitted whenever the `input` stream is resumed. Emitted whenever the `input` stream is resumed.
Example of listening for `resume`: Example of listening for `'resume'`:
rl.on('resume', function() { rl.on('resume', function() {
console.log('Readline resumed.'); console.log('Readline resumed.');
@ -191,10 +192,10 @@ Emitted whenever the `input` stream receives a `^Z`, respectively known as
`SIGTSTP`. If there is no `SIGTSTP` event listener present when the `input` `SIGTSTP`. If there is no `SIGTSTP` event listener present when the `input`
stream receives a `SIGTSTP`, the program will be sent to the background. stream receives a `SIGTSTP`, the program will be sent to the background.
When the program is resumed with `fg`, the `pause` and `SIGCONT` events will be When the program is resumed with `fg`, the `'pause'` and `SIGCONT` events will be
emitted. You can use either to resume the stream. emitted. You can use either to resume the stream.
The `pause` and `SIGCONT` events will not be triggered if the stream was paused The `'pause'` and `SIGCONT` events will not be triggered if the stream was paused
before the program was sent to the background. before the program was sent to the background.
Example of listening for `SIGTSTP`: Example of listening for `SIGTSTP`:
@ -246,7 +247,7 @@ Clears the screen from the current position of the cursor down.
## readline.createInterface(options) ## readline.createInterface(options)
Creates a readline `Interface` instance. Accepts an "options" Object that takes Creates a readline `Interface` instance. Accepts an `options Object that takes
the following values: the following values:
- `input` - the readable stream to listen to (Required). - `input` - the readable stream to listen to (Required).
@ -287,8 +288,8 @@ Also `completer` can be run in async mode if it accepts two arguments:
callback(null, [['123'], linePartial]); callback(null, [['123'], linePartial]);
} }
`createInterface` is commonly used with `process.stdin` and `createInterface` is commonly used with [`process.stdin`][] and
`process.stdout` in order to accept user input: [`process.stdout`][] in order to accept user input:
var readline = require('readline'); var readline = require('readline');
var rl = readline.createInterface({ var rl = readline.createInterface({
@ -297,12 +298,12 @@ Also `completer` can be run in async mode if it accepts two arguments:
}); });
Once you have a readline instance, you most commonly listen for the Once you have a readline instance, you most commonly listen for the
`"line"` event. `'line'` event.
If `terminal` is `true` for this instance then the `output` stream will get If `terminal` is `true` for this instance then the `output` stream will get
the best compatibility if it defines an `output.columns` property, and fires the best compatibility if it defines an `output.columns` property, and fires
a `"resize"` event on the `output` if/when the columns ever change a `'resize'` event on the `output` if/when the columns ever change
(`process.stdout` does this automatically when it is a TTY). ([`process.stdout`][] does this automatically when it is a TTY).
## readline.cursorTo(stream, x, y) ## readline.cursorTo(stream, x, y)
@ -311,3 +312,6 @@ Move cursor to the specified position in a given TTY stream.
## readline.moveCursor(stream, dx, dy) ## readline.moveCursor(stream, dx, dy)
Move cursor relative to it's current position in a given TTY stream. Move cursor relative to it's current position in a given TTY stream.
[`process.stdin`]: process.html#process_process_stdin
[`process.stdout`]: process.html#process_process_stdout

16
doc/api/repl.markdown

@ -120,7 +120,7 @@ The following key combinations in the REPL have these special effects:
### Customizing Object displays in the REPL ### Customizing Object displays in the REPL
The REPL module internally uses The REPL module internally uses
[util.inspect()][], when printing values. However, `util.inspect` delegates the [`util.inspect()`][], when printing values. However, `util.inspect` delegates the
call to the object's `inspect()` function, if it has one. You can read more call to the object's `inspect()` function, if it has one. You can read more
about this delegation [here][]. about this delegation [here][].
@ -147,8 +147,8 @@ This inherits from [Readline Interface][] with the following events:
`function () {}` `function () {}`
Emitted when the user exits the REPL in any of the defined ways. Namely, typing Emitted when the user exits the REPL in any of the defined ways. Namely, typing
`.exit` at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D `.exit` at the repl, pressing Ctrl+C twice to signal `SIGINT`, or pressing Ctrl+D
to signal "end" on the `input` stream. to signal `'end'` on the `input` stream.
Example of listening for `exit`: Example of listening for `exit`:
@ -216,8 +216,8 @@ Example of invoking that command from the REPL:
* `preserveCursor` {Boolean} * `preserveCursor` {Boolean}
Like [readline.prompt][] except also adding indents with ellipses when inside Like [`readline.prompt`][] except also adding indents with ellipses when inside
blocks. The `preserveCursor` argument is passed to [readline.prompt][]. This is blocks. The `preserveCursor` argument is passed to [`readline.prompt`][]. This is
used primarily with `defineCommand`. It's also used internally to render each used primarily with `defineCommand`. It's also used internally to render each
prompt line. prompt line.
@ -323,7 +323,7 @@ a `net.Server` and `net.Socket` instance, see: https://gist.github.com/2209310
For an example of running a REPL instance over `curl(1)`, For an example of running a REPL instance over `curl(1)`,
see: https://gist.github.com/2053342 see: https://gist.github.com/2053342
[Readline Interface]: readline.html#readline_class_interface [`readline.prompt`]: readline.html#readline_rl_prompt_preservecursor
[readline.prompt]: readline.html#readline_rl_prompt_preservecursor [`util.inspect()`]: util.html#util_util_inspect_object_options
[util.inspect()]: util.html#util_util_inspect_object_options
[here]: util.html#util_custom_inspect_function_on_objects [here]: util.html#util_custom_inspect_function_on_objects
[Readline Interface]: readline.html#readline_class_interface

138
doc/api/stream.markdown

@ -4,8 +4,8 @@
A stream is an abstract interface implemented by various objects in A stream is an abstract interface implemented by various objects in
Node.js. For example a [request to an HTTP server][] is a stream, as is Node.js. For example a [request to an HTTP server][] is a stream, as is
[stdout][]. Streams are readable, writable, or both. All streams are [`stdout`][]. Streams are readable, writable, or both. All streams are
instances of [EventEmitter][] instances of [`EventEmitter`][].
You can load the Stream base classes by doing `require('stream')`. You can load the Stream base classes by doing `require('stream')`.
There are base classes provided for [Readable][] streams, [Writable][] There are base classes provided for [Readable][] streams, [Writable][]
@ -126,7 +126,7 @@ mode, then data will be lost.
You can switch to flowing mode by doing any of the following: You can switch to flowing mode by doing any of the following:
* Adding a [`'data'` event][] handler to listen for data. * Adding a [`'data'`][] event handler to listen for data.
* Calling the [`resume()`][] method to explicitly open the flow. * Calling the [`resume()`][] method to explicitly open the flow.
* Calling the [`pipe()`][] method to send the data to a [Writable][]. * Calling the [`pipe()`][] method to send the data to a [Writable][].
@ -134,7 +134,7 @@ You can switch back to paused mode by doing either of the following:
* If there are no pipe destinations, by calling the [`pause()`][] * If there are no pipe destinations, by calling the [`pause()`][]
method. method.
* If there are pipe destinations, by removing any [`'data'` event][] * If there are pipe destinations, by removing any [`'data'`][] event
handlers, and removing all pipe destinations by calling the handlers, and removing all pipe destinations by calling the
[`unpipe()`][] method. [`unpipe()`][] method.
@ -153,7 +153,7 @@ Examples of readable streams include:
* [crypto streams][] * [crypto streams][]
* [tcp sockets][] * [tcp sockets][]
* [child process stdout and stderr][] * [child process stdout and stderr][]
* [process.stdin][] * [`process.stdin`][]
#### Event: 'close' #### Event: 'close'
@ -161,13 +161,13 @@ Emitted when the stream and any of its underlying resources (a file
descriptor, for example) have been closed. The event indicates that descriptor, for example) have been closed. The event indicates that
no more events will be emitted, and no further computation will occur. no more events will be emitted, and no further computation will occur.
Not all streams will emit the 'close' event. Not all streams will emit the `'close'` event.
#### Event: 'data' #### Event: 'data'
* `chunk` {Buffer | String} The chunk of data. * `chunk` {Buffer | String} The chunk of data.
Attaching a `data` event listener to a stream that has not been Attaching a `'data'` event listener to a stream that has not been
explicitly paused will switch the stream into flowing mode. Data will explicitly paused will switch the stream into flowing mode. Data will
then be passed as soon as it is available. then be passed as soon as it is available.
@ -185,7 +185,7 @@ readable.on('data', function(chunk) {
This event fires when there will be no more data to read. This event fires when there will be no more data to read.
Note that the `end` event **will not fire** unless the data is Note that the `'end'` event **will not fire** unless the data is
completely consumed. This can be done by switching into flowing mode, completely consumed. This can be done by switching into flowing mode,
or by calling `read()` repeatedly until you get to the end. or by calling `read()` repeatedly until you get to the end.
@ -221,13 +221,13 @@ readable.on('readable', function() {
}); });
``` ```
Once the internal buffer is drained, a `readable` event will fire Once the internal buffer is drained, a `'readable'` event will fire
again when more data is available. again when more data is available.
The `readable` event is not emitted in the "flowing" mode with the The `'readable'` event is not emitted in the "flowing" mode with the
sole exception of the last one, on end-of-stream. sole exception of the last one, on end-of-stream.
The 'readable' event indicates that the stream has new information: The `'readable'` event indicates that the stream has new information:
either new data is available or the end of the stream has been reached. either new data is available or the end of the stream has been reached.
In the former case, `.read()` will return that data. In the latter case, In the former case, `.read()` will return that data. In the latter case,
`.read()` will return null. For instance, in the following example, `foo.txt` `.read()` will return null. For instance, in the following example, `foo.txt`
@ -275,7 +275,7 @@ readable.isPaused() // === false
* Return: `this` * Return: `this`
This method will cause a stream in flowing mode to stop emitting This method will cause a stream in flowing mode to stop emitting
`data` events, switching out of flowing mode. Any data that becomes `'data'` events, switching out of flowing mode. Any data that becomes
available will remain in the internal buffer. available will remain in the internal buffer.
```javascript ```javascript
@ -375,9 +375,9 @@ readable.on('readable', function() {
``` ```
If this method returns a data chunk, then it will also trigger the If this method returns a data chunk, then it will also trigger the
emission of a [`'data'` event][]. emission of a [`'data'`][] event.
Note that calling `readable.read([size])` after the `end` event has been Note that calling `readable.read([size])` after the `'end'` event has been
triggered will return `null`. No runtime error will be raised. triggered will return `null`. No runtime error will be raised.
#### readable.resume() #### readable.resume()
@ -389,7 +389,7 @@ events.
This method will switch the stream into flowing mode. If you do *not* This method will switch the stream into flowing mode. If you do *not*
want to consume the data from a stream, but you *do* want to get to want to consume the data from a stream, but you *do* want to get to
its `end` event, you can call [`readable.resume()`][] to open the flow of its `'end'` event, you can call [`readable.resume()`][] to open the flow of
data. data.
```javascript ```javascript
@ -460,7 +460,7 @@ parser, which needs to "un-consume" some data that it has
optimistically pulled out of the source, so that the stream can be optimistically pulled out of the source, so that the stream can be
passed on to some other party. passed on to some other party.
Note that `stream.unshift(chunk)` cannot be called after the `end` event Note that `stream.unshift(chunk)` cannot be called after the `'end'` event
has been triggered; a runtime error will be raised. has been triggered; a runtime error will be raised.
If you find that you must often call `stream.unshift(chunk)` in your If you find that you must often call `stream.unshift(chunk)` in your
@ -565,11 +565,11 @@ Examples of writable streams include:
* [crypto streams][] * [crypto streams][]
* [tcp sockets][] * [tcp sockets][]
* [child process stdin][] * [child process stdin][]
* [process.stdout][], [process.stderr][] * [`process.stdout`][], [`process.stderr`][]
#### Event: 'drain' #### Event: 'drain'
If a [`writable.write(chunk)`][] call returns false, then the `drain` If a [`writable.write(chunk)`][] call returns false, then the `'drain'`
event will indicate when it is appropriate to begin writing more data event will indicate when it is appropriate to begin writing more data
to the stream. to the stream.
@ -671,7 +671,7 @@ Buffered data will be flushed either at `.uncork()` or at `.end()` call.
* `callback` {Function} Optional callback for when the stream is finished * `callback` {Function} Optional callback for when the stream is finished
Call this method when no more data will be written to the stream. If Call this method when no more data will be written to the stream. If
supplied, the callback is attached as a listener on the `finish` event. supplied, the callback is attached as a listener on the `'finish'` event.
Calling [`write()`][] after calling [`end()`][] will raise an error. Calling [`write()`][] after calling [`end()`][] will raise an error.
@ -710,7 +710,7 @@ If the data had to be buffered internally, then it will return
This return value is strictly advisory. You MAY continue to write, This return value is strictly advisory. You MAY continue to write,
even if it returns `false`. However, writes will be buffered in even if it returns `false`. However, writes will be buffered in
memory, so it is best not to do this excessively. Instead, wait for memory, so it is best not to do this excessively. Instead, wait for
the `drain` event before writing more data. the `'drain'` event before writing more data.
## API for Stream Implementors ## API for Stream Implementors
@ -1118,8 +1118,8 @@ initialized.
#### Events: 'finish' and 'end' #### Events: 'finish' and 'end'
The [`finish`][] and [`end`][] events are from the parent Writable The [`'finish'`][] and [`'end'`][] events are from the parent Writable
and Readable classes respectively. The `finish` event is fired after and Readable classes respectively. The `'finish'` event is fired after
`.end()` is called and all chunks have been processed by `_transform`, `.end()` is called and all chunks have been processed by `_transform`,
`end` is fired after all data has been output which is after the callback `end` is fired after all data has been output which is after the callback
in `_flush` has been called. in `_flush` has been called.
@ -1510,7 +1510,7 @@ no longer have to worry about losing `'data'` chunks.
Most programs will continue to function normally. However, this Most programs will continue to function normally. However, this
introduces an edge case in the following conditions: introduces an edge case in the following conditions:
* No [`'data'` event][] handler is added. * No [`'data'`][] event handler is added.
* The [`resume()`][] method is never called. * The [`resume()`][] method is never called.
* The stream is not piped to any writable destination. * The stream is not piped to any writable destination.
@ -1671,60 +1671,60 @@ code) will know when to check again, by calling `stream.read(0)`. In
those cases, you *may* call `stream.push('')`. those cases, you *may* call `stream.push('')`.
So far, the only use case for this functionality is in the So far, the only use case for this functionality is in the
[tls.CryptoStream][] class, which is deprecated in Node.js/io.js v1.0. If you [`tls.CryptoStream`][] class, which is deprecated in Node.js/io.js v1.0. If you
find that you have to use `stream.push('')`, please consider another find that you have to use `stream.push('')`, please consider another
approach, because it almost certainly indicates that something is approach, because it almost certainly indicates that something is
horribly wrong. horribly wrong.
[request to an HTTP server]: http.html#http_http_incomingmessage [_read]: #stream_readable_read_size_1
[EventEmitter]: events.html#events_class_events_eventemitter [_write]: #stream_writable_write_chunk_encoding_callback_1
[Object mode]: #stream_object_mode [`'data'`]: #stream_event_data
[`'end'`]: #stream_event_end
[`'finish'`]: #stream_event_finish
[`_read()`]: #stream_readable_read_size_1
[`_read(size)`]: #stream_readable_read_size_1
[`_write()`]: #stream_writable_write_chunk_encoding_callback_1
[`_write(chunk, encoding, callback)`]: #stream_writable_write_chunk_encoding_callback_1
[`end()`]: #stream_writable_end_chunk_encoding_callback
[`EventEmitter`]: events.html#events_class_events_eventemitter
[`pause()`]: #stream_readable_pause
[`pipe()`]: #stream_readable_pipe_destination_options
[`process.stderr`]: process.html#process_process_stderr
[`process.stdin`]: process.html#process_process_stdin
[`process.stdout`]: process.html#process_process_stdout
[`readable.resume()`]: #stream_readable_resume
[`resume()`]: #stream_readable_resume
[`stdout`]: process.html#process_process_stdout
[`stream.push()`]: #stream_readable_push_chunk_encoding
[`stream.push(chunk)`]: #stream_readable_push_chunk_encoding [`stream.push(chunk)`]: #stream_readable_push_chunk_encoding
[`stream.push(null)`]: #stream_readable_push_chunk_encoding [`stream.push(null)`]: #stream_readable_push_chunk_encoding
[`stream.push()`]: #stream_readable_push_chunk_encoding [`stream.write(chunk)`]: #stream_writable_write_chunk_encoding_callback
[`tls.CryptoStream`]: tls.html#tls_class_cryptostream
[`unpipe()`]: #stream_readable_unpipe_destination [`unpipe()`]: #stream_readable_unpipe_destination
[unpiped]: #stream_readable_unpipe_destination [`unpipe()`]: #stream_readable_unpipe_destination
[tcp sockets]: net.html#net_class_net_socket [`util.inherits`]: util.html#util_util_inherits_constructor_superconstructor
[http responses, on the client]: http.html#http_http_incomingmessage [`writable.write(chunk)`]: #stream_writable_write_chunk_encoding_callback
[http requests, on the server]: http.html#http_http_incomingmessage [`write()`]: #stream_writable_write_chunk_encoding_callback
[http requests, on the client]: http.html#http_class_http_clientrequest [`write(chunk, encoding, callback)`]: #stream_writable_write_chunk_encoding_callback
[http responses, on the server]: http.html#http_class_http_serverresponse
[fs read streams]: fs.html#fs_class_fs_readstream
[fs write streams]: fs.html#fs_class_fs_writestream
[zlib streams]: zlib.html
[zlib]: zlib.html
[crypto streams]: crypto.html
[crypto]: crypto.html
[tls.CryptoStream]: tls.html#tls_class_cryptostream
[process.stdin]: process.html#process_process_stdin
[stdout]: process.html#process_process_stdout
[process.stdout]: process.html#process_process_stdout
[process.stderr]: process.html#process_process_stderr
[child process stdout and stderr]: child_process.html#child_process_child_stdout
[child process stdin]: child_process.html#child_process_child_stdin
[API for Stream Consumers]: #stream_api_for_stream_consumers [API for Stream Consumers]: #stream_api_for_stream_consumers
[API for Stream Implementors]: #stream_api_for_stream_implementors [API for Stream Implementors]: #stream_api_for_stream_implementors
[Readable]: #stream_class_stream_readable [child process stdin]: child_process.html#child_process_child_stdin
[Writable]: #stream_class_stream_writable [child process stdout and stderr]: child_process.html#child_process_child_stdout
[crypto streams]: crypto.html
[crypto]: crypto.html
[Duplex]: #stream_class_stream_duplex [Duplex]: #stream_class_stream_duplex
[fs read streams]: fs.html#fs_class_fs_readstream
[fs write streams]: fs.html#fs_class_fs_writestream
[http requests, on the client]: http.html#http_class_http_clientrequest
[http requests, on the server]: http.html#http_http_incomingmessage
[http responses, on the client]: http.html#http_http_incomingmessage
[http responses, on the server]: http.html#http_class_http_serverresponse
[Object mode]: #stream_object_mode
[Readable]: #stream_class_stream_readable
[request to an HTTP server]: http.html#http_http_incomingmessage
[tcp sockets]: net.html#net_class_net_socket
[Transform]: #stream_class_stream_transform [Transform]: #stream_class_stream_transform
[`end`]: #stream_event_end [unpiped]: #stream_readable_unpipe_destination
[`finish`]: #stream_event_finish [Writable]: #stream_class_stream_writable
[`_read(size)`]: #stream_readable_read_size_1 [zlib streams]: zlib.html
[`_read()`]: #stream_readable_read_size_1 [zlib]: zlib.html
[_read]: #stream_readable_read_size_1
[`writable.write(chunk)`]: #stream_writable_write_chunk_encoding_callback
[`write(chunk, encoding, callback)`]: #stream_writable_write_chunk_encoding_callback
[`write()`]: #stream_writable_write_chunk_encoding_callback
[`stream.write(chunk)`]: #stream_writable_write_chunk_encoding_callback
[`_write(chunk, encoding, callback)`]: #stream_writable_write_chunk_encoding_callback_1
[`_write()`]: #stream_writable_write_chunk_encoding_callback_1
[_write]: #stream_writable_write_chunk_encoding_callback_1
[`util.inherits`]: util.html#util_util_inherits_constructor_superconstructor
[`end()`]: #stream_writable_end_chunk_encoding_callback
[`'data'` event]: #stream_event_data
[`resume()`]: #stream_readable_resume
[`readable.resume()`]: #stream_readable_resume
[`pause()`]: #stream_readable_pause
[`unpipe()`]: #stream_readable_unpipe_destination
[`pipe()`]: #stream_readable_pipe_destination_options

2
doc/api/string_decoder.markdown

@ -17,7 +17,7 @@ additional support for utf8.
## Class: StringDecoder ## Class: StringDecoder
Accepts a single argument, `encoding` which defaults to `utf8`. Accepts a single argument, `encoding` which defaults to `'utf8'`.
### decoder.end() ### decoder.end()

2
doc/api/synopsis.markdown

@ -3,7 +3,7 @@
<!--type=misc--> <!--type=misc-->
An example of a [web server][] written with Node.js which responds with An example of a [web server][] written with Node.js which responds with
'Hello World': `'Hello World'`:
var http = require('http'); var http = require('http');

7
doc/api/timers.markdown

@ -28,7 +28,7 @@ Returns the timer.
## setImmediate(callback[, arg][, ...]) ## setImmediate(callback[, arg][, ...])
To schedule the "immediate" execution of `callback` after I/O events To schedule the "immediate" execution of `callback` after I/O events
callbacks and before `setTimeout` and `setInterval` . Returns an callbacks and before [`setTimeout`][] and [`setInterval`][]. Returns an
`immediateObject` for possible use with `clearImmediate()`. Optionally you `immediateObject` for possible use with `clearImmediate()`. Optionally you
can also pass arguments to the callback. can also pass arguments to the callback.
@ -64,7 +64,7 @@ immediately, as if the `delay` was set to 1.
## unref() ## unref()
The opaque value returned by `setTimeout` and `setInterval` also has the method The opaque value returned by [`setTimeout`][] and [`setInterval`][] also has the method
`timer.unref()` which will allow you to create a timer that is active but if `timer.unref()` which will allow you to create a timer that is active but if
it is the only item left in the event loop, it won't keep the program running. it is the only item left in the event loop, it won't keep the program running.
If the timer is already `unref`d calling `unref` again will have no effect. If the timer is already `unref`d calling `unref` again will have no effect.
@ -74,3 +74,6 @@ will wakeup the event loop, creating too many of these may adversely effect
event loop performance -- use wisely. event loop performance -- use wisely.
Returns the timer. Returns the timer.
[`setInterval`]: timers.html#timers_setinterval_callback_delay_arg
[`setTimeout`]: timers.html#timers_settimeout_callback_delay_arg

28
doc/api/tls.markdown

@ -159,7 +159,7 @@ Returned by tls.createSecurePair.
The event is emitted from the SecurePair once the pair has successfully The event is emitted from the SecurePair once the pair has successfully
established a secure connection. established a secure connection.
Similarly to the checking for the server 'secureConnection' event, Similarly to the checking for the server `'secureConnection'` event,
pair.cleartext.authorized should be checked to confirm whether the certificate pair.cleartext.authorized should be checked to confirm whether the certificate
used properly authorized. used properly authorized.
@ -173,7 +173,7 @@ connections using TLS or SSL.
`function (exception, tlsSocket) { }` `function (exception, tlsSocket) { }`
When a client connection emits an 'error' event before secure connection is When a client connection emits an `'error'` event before secure connection is
established - it will be forwarded here. established - it will be forwarded here.
`tlsSocket` is the [tls.TLSSocket][] that the error originated from. `tlsSocket` is the [tls.TLSSocket][] that the error originated from.
@ -207,9 +207,9 @@ Calling `callback(err)` will result in a `socket.destroy(err)` call.
Typical flow: Typical flow:
1. Client connects to server and sends `OCSPRequest` to it (via status info 1. Client connects to server and sends `'OCSPRequest'` to it (via status info
extension in ClientHello.) extension in ClientHello.)
2. Server receives request and invokes `OCSPRequest` event listener if present 2. Server receives request and invokes `'OCSPRequest'` event listener if present
3. Server grabs OCSP url from either `certificate` or `issuer` and performs an 3. Server grabs OCSP url from either `certificate` or `issuer` and performs an
[OCSP request] to the CA [OCSP request] to the CA
4. Server receives `OCSPResponse` from CA and sends it back to client via 4. Server receives `OCSPResponse` from CA and sends it back to client via
@ -333,7 +333,7 @@ gets high.
## Class: tls.TLSSocket ## Class: tls.TLSSocket
This is a wrapped version of [net.Socket][] that does transparent encryption This is a wrapped version of [`net.Socket`][] that does transparent encryption
of written data and all required TLS negotiation. of written data and all required TLS negotiation.
This instance implements a duplex [Stream][] interfaces. It has all the This instance implements a duplex [Stream][] interfaces. It has all the
@ -346,7 +346,7 @@ only return data while the connection is open.
Construct a new TLSSocket object from existing TCP socket. Construct a new TLSSocket object from existing TCP socket.
`socket` is an instance of [net.Socket][] `socket` is an instance of [`net.Socket`][]
`options` is an optional object that might contain following properties: `options` is an optional object that might contain following properties:
@ -356,7 +356,7 @@ Construct a new TLSSocket object from existing TCP socket.
- `isServer`: If `true` - TLS socket will be instantiated in server-mode. - `isServer`: If `true` - TLS socket will be instantiated in server-mode.
Default: `false` Default: `false`
- `server`: An optional [net.Server][] instance - `server`: An optional [`net.Server`][] instance
- `requestCert`: Optional, see [tls.createSecurePair][] - `requestCert`: Optional, see [tls.createSecurePair][]
@ -371,7 +371,7 @@ Construct a new TLSSocket object from existing TCP socket.
- `session`: Optional, a `Buffer` instance, containing TLS session - `session`: Optional, a `Buffer` instance, containing TLS session
- `requestOCSP`: Optional, if `true` - OCSP status request extension would - `requestOCSP`: Optional, if `true` - OCSP status request extension would
be added to client hello, and `OCSPResponse` event will be emitted on socket be added to client hello, and `'OCSPResponse'` event will be emitted on socket
before establishing secure communication before establishing secure communication
### Event: 'OCSPResponse' ### Event: 'OCSPResponse'
@ -605,7 +605,7 @@ Creates a new client connection to the given `port` and `host` (old API) or
error. Default: 1024. error. Default: 1024.
The `callback` parameter will be added as a listener for the The `callback` parameter will be added as a listener for the
['secureConnect'][] event. [`'secureConnect'`][] event.
`tls.connect()` returns a [tls.TLSSocket][] object. `tls.connect()` returns a [tls.TLSSocket][] object.
@ -719,7 +719,7 @@ NOTE: `cleartext` has the same APIs as [tls.TLSSocket][]
## tls.createServer(options[, secureConnectionListener]) ## tls.createServer(options[, secureConnectionListener])
Creates a new [tls.Server][]. The `connectionListener` argument is Creates a new [tls.Server][]. The `connectionListener` argument is
automatically set as a listener for the [secureConnection][] event. The automatically set as a listener for the [`'secureConnection'`][] event. The
`options` object has these possibilities: `options` object has these possibilities:
- `pfx`: A string or `Buffer` containing the private key, certificate and - `pfx`: A string or `Buffer` containing the private key, certificate and
@ -922,11 +922,11 @@ Example:
[tls.createServer]: #tls_tls_createserver_options_secureconnectionlistener [tls.createServer]: #tls_tls_createserver_options_secureconnectionlistener
[tls.createSecurePair]: #tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options [tls.createSecurePair]: #tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options
[tls.TLSSocket]: #tls_class_tls_tlssocket [tls.TLSSocket]: #tls_class_tls_tlssocket
[net.Server]: net.html#net_class_net_server [`net.Server`]: net.html#net_class_net_server
[net.Socket]: net.html#net_class_net_socket [`net.Socket`]: net.html#net_class_net_socket
[net.Server.address()]: net.html#net_server_address [net.Server.address()]: net.html#net_server_address
['secureConnect']: #tls_event_secureconnect [`'secureConnect'`]: #tls_event_secureconnect
[secureConnection]: #tls_event_secureconnection [`'secureConnection'`]: #tls_event_secureconnection
[Perfect Forward Secrecy]: #tls_perfect_forward_secrecy [Perfect Forward Secrecy]: #tls_perfect_forward_secrecy
[Stream]: stream.html#stream_stream [Stream]: stream.html#stream_stream
[SSL_METHODS]: http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS [SSL_METHODS]: http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS

4
doc/api/tty.markdown

@ -53,12 +53,12 @@ has changed.
### ws.columns ### ws.columns
A `Number` that gives the number of columns the TTY currently has. This property A `Number` that gives the number of columns the TTY currently has. This property
gets updated on "resize" events. gets updated on `'resize'` events.
### ws.rows ### ws.rows
A `Number` that gives the number of rows the TTY currently has. This property A `Number` that gives the number of rows the TTY currently has. This property
gets updated on "resize" events. gets updated on `'resize'` events.
## tty.isatty(fd) ## tty.isatty(fd)

6
doc/api/util.markdown

@ -233,7 +233,7 @@ formatted according to the returned Object. This is similar to how
Stability: 0 - Deprecated Stability: 0 - Deprecated
Internal alias for Array.isArray. Internal alias for [`Array.isArray`][].
Returns `true` if the given "object" is an `Array`. `false` otherwise. Returns `true` if the given "object" is an `Array`. `false` otherwise.
@ -297,7 +297,7 @@ Returns `true` if the given "object" is a `Date`. `false` otherwise.
Stability: 0 - Deprecated Stability: 0 - Deprecated
Returns `true` if the given "object" is an `Error`. `false` otherwise. Returns `true` if the given "object" is an [`Error`][]. `false` otherwise.
var util = require('util'); var util = require('util');
@ -499,4 +499,6 @@ Deprecated predecessor of `console.log`.
Deprecated predecessor of `console.log`. Deprecated predecessor of `console.log`.
[`Array.isArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
[constructor]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor [constructor]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor
[`Error`]: errors.html#errors_class_error

7
doc/api/vm.markdown

@ -35,7 +35,7 @@ The options when creating a script are:
Applies only to syntax errors compiling the code; errors while running the Applies only to syntax errors compiling the code; errors while running the
code are controlled by the options to the script's methods. code are controlled by the options to the script's methods.
- `timeout`: a number of milliseconds to execute `code` before terminating - `timeout`: a number of milliseconds to execute `code` before terminating
execution. If execution is terminated, an `Error` will be thrown. execution. If execution is terminated, an [`Error`][] will be thrown.
### script.runInContext(contextifiedSandbox[, options]) ### script.runInContext(contextifiedSandbox[, options])
@ -141,7 +141,7 @@ The options for running a script are:
Applies only to runtime errors executing the code; it is impossible to create Applies only to runtime errors executing the code; it is impossible to create
a `Script` instance with syntax errors, as the constructor will throw. a `Script` instance with syntax errors, as the constructor will throw.
- `timeout`: a number of milliseconds to execute the script before terminating - `timeout`: a number of milliseconds to execute the script before terminating
execution. If execution is terminated, an `Error` will be thrown. execution. If execution is terminated, an [`Error`][] will be thrown.
## vm.createContext([sandbox]) ## vm.createContext([sandbox])
@ -273,7 +273,8 @@ e.g. `(0,eval)('code')`. However, it also has the following additional options:
Will capture both syntax errors from compiling `code` and runtime errors Will capture both syntax errors from compiling `code` and runtime errors
thrown by executing the compiled code. Defaults to `true`. thrown by executing the compiled code. Defaults to `true`.
- `timeout`: a number of milliseconds to execute `code` before terminating - `timeout`: a number of milliseconds to execute `code` before terminating
execution. If execution is terminated, an `Error` will be thrown. execution. If execution is terminated, an [`Error`][] will be thrown.
[indirect `eval` call]: http://es5.github.io/#x10.4.2 [indirect `eval` call]: http://es5.github.io/#x10.4.2
[global object]: http://es5.github.io/#x15.1 [global object]: http://es5.github.io/#x15.1
[`Error`]: errors.html#errors_class_error

Loading…
Cancel
Save