From ecd217987b185c092ebad9abb82d7fcf1d651de9 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 10:48:45 -0500 Subject: [PATCH 01/32] doc: sort assert alphabetically Reorders, with no contextual changes, the assert documentation alphabetically. --- doc/api/assert.markdown | 108 ++++++++++++++++++++-------------------- 1 file changed, 54 insertions(+), 54 deletions(-) diff --git a/doc/api/assert.markdown b/doc/api/assert.markdown index b81037287b499b..a607b92ead197f 100644 --- a/doc/api/assert.markdown +++ b/doc/api/assert.markdown @@ -6,25 +6,11 @@ This module is used so that Node.js can test itself. It can be accessed with `require('assert')`. However, it is recommended that a userland assertion library be used instead. -## assert.fail(actual, expected, message, operator) - -Throws an exception that displays the values for `actual` and `expected` -separated by the provided operator. - ## assert(value[, message]), assert.ok(value[, message]) Tests if value is truthy. It is equivalent to `assert.equal(!!value, true, message)`. -## assert.equal(actual, expected[, message]) - -Tests shallow, coercive equality with the equal comparison operator ( `==` ). - -## assert.notEqual(actual, expected[, message]) - -Tests shallow, coercive inequality with the not equal comparison operator -( `!=` ). - ## assert.deepEqual(actual, expected[, message]) Tests for deep equality. Primitive values are compared with the equal @@ -39,27 +25,72 @@ non-enumerable: // WARNING: This does not throw an AssertionError! assert.deepEqual(Error('a'), Error('b')); +## assert.deepStrictEqual(actual, expected[, message]) + +Tests for deep equality. Primitive values are compared with the strict equality +operator ( `===` ). + +## assert.doesNotThrow(block[, error][, message]) + +Expects `block` not to throw an error. See [assert.throws()](#assert_assert_throws_block_error_message) for more details. + +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 +throw the `TypeError`, since we're not matching the error types in the +assertion. + + assert.doesNotThrow( + function() { + throw new TypeError("Wrong value"); + }, + SyntaxError + ); + +In case `error` matches with the error thrown by `block`, an `AssertionError` +is thrown instead. + + assert.doesNotThrow( + function() { + throw new TypeError("Wrong value"); + }, + TypeError + ); + +## assert.equal(actual, expected[, message]) + +Tests shallow, coercive equality with the equal comparison operator ( `==` ). + +## assert.fail(actual, expected, message, operator) + +Throws an exception that displays the values for `actual` and `expected` +separated by the provided operator. + +## assert.ifError(value) + +Throws `value` if `value` is truthy. This is useful when testing the `error` +argument in callbacks. + ## assert.notDeepEqual(actual, expected[, message]) Tests for any deep inequality. Opposite of `assert.deepEqual`. -## assert.strictEqual(actual, expected[, message]) +## assert.notDeepStrictEqual(actual, expected[, message]) -Tests strict equality as determined by the strict equality operator ( `===` ). +Tests for deep inequality. Opposite of `assert.deepStrictEqual`. + +## assert.notEqual(actual, expected[, message]) + +Tests shallow, coercive inequality with the not equal comparison operator +( `!=` ). ## assert.notStrictEqual(actual, expected[, message]) Tests strict inequality as determined by the strict not equal operator ( `!==` ). -## assert.deepStrictEqual(actual, expected[, message]) - -Tests for deep equality. Primitive values are compared with the strict equality -operator ( `===` ). - -## assert.notDeepStrictEqual(actual, expected[, message]) +## assert.strictEqual(actual, expected[, message]) -Tests for deep inequality. Opposite of `assert.deepStrictEqual`. +Tests strict equality as determined by the strict equality operator ( `===` ). ## assert.throws(block[, error][, message]) @@ -97,34 +128,3 @@ Custom error validation: }, "unexpected error" ); - -## assert.doesNotThrow(block[, error][, message]) - -Expects `block` not to throw an error. See [assert.throws()](#assert_assert_throws_block_error_message) for more details. - -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 -throw the `TypeError`, since we're not matching the error types in the -assertion. - - assert.doesNotThrow( - function() { - throw new TypeError("Wrong value"); - }, - SyntaxError - ); - -In case `error` matches with the error thrown by `block`, an `AssertionError` -is thrown instead. - - assert.doesNotThrow( - function() { - throw new TypeError("Wrong value"); - }, - TypeError - ); - -## assert.ifError(value) - -Throws `value` if `value` is truthy. This is useful when testing the `error` -argument in callbacks. From 63a2e5588ace2928a9e1ad2d709de4653ce22ebf Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 10:49:28 -0500 Subject: [PATCH 02/32] doc: sort buffer alphabetically Reorders, with minimal contextual duplication, the buffer documentation alphabetically. --- doc/api/buffer.markdown | 703 +++++++++++++++++++++------------------- 1 file changed, 366 insertions(+), 337 deletions(-) diff --git a/doc/api/buffer.markdown b/doc/api/buffer.markdown index c678c4a2da8b13..a401d5a7d46b0e 100644 --- a/doc/api/buffer.markdown +++ b/doc/api/buffer.markdown @@ -57,6 +57,18 @@ arrays specification. `ArrayBuffer#slice()` makes a copy of the slice while The Buffer class is a global type for dealing with binary data directly. It can be constructed in a variety of ways. +### new Buffer(array) + +* `array` Array + +Allocates a new buffer using an `array` of octets. + +### new Buffer(buffer) + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + ### new Buffer(size) * `size` Number @@ -70,18 +82,6 @@ Unlike `ArrayBuffers`, the underlying memory for buffers is not initialized. So the contents of a newly created `Buffer` are unknown and could contain sensitive data. Use `buf.fill(0)` to initialize a buffer to zeroes. -### new Buffer(array) - -* `array` Array - -Allocates a new buffer using an `array` of octets. - -### new Buffer(buffer) - -* `buffer` {Buffer} - -Copies the passed `buffer` data onto a new `Buffer` instance. - ### new Buffer(str[, encoding]) * `str` String - string to encode. @@ -90,20 +90,6 @@ Copies the passed `buffer` data onto a new `Buffer` instance. Allocates a new buffer containing the given `str`. `encoding` defaults to `'utf8'`. -### Class Method: Buffer.isEncoding(encoding) - -* `encoding` {String} The encoding string to test - -Returns true if the `encoding` is a valid encoding argument, or false -otherwise. - -### Class Method: Buffer.isBuffer(obj) - -* `obj` Object -* Return: Boolean - -Tests if `obj` is a `Buffer`. - ### Class Method: Buffer.byteLength(string[, encoding]) * `string` String @@ -123,6 +109,17 @@ Example: // ½ + ¼ = ¾: 9 characters, 12 bytes +### Class Method: Buffer.compare(buf1, buf2) + +* `buf1` {Buffer} +* `buf2` {Buffer} + +The same as [`buf1.compare(buf2)`](#buffer_buf_compare_otherbuffer). Useful +for sorting an Array of Buffers: + + var arr = [Buffer('1234'), Buffer('0123')]; + arr.sort(Buffer.compare); + ### Class Method: Buffer.concat(list[, totalLength]) * `list` {Array} List of Buffer objects to concat @@ -164,151 +161,32 @@ Example: build a single buffer from a list of three buffers: // // 42 -### Class Method: Buffer.compare(buf1, buf2) - -* `buf1` {Buffer} -* `buf2` {Buffer} - -The same as [`buf1.compare(buf2)`](#buffer_buf_compare_otherbuffer). Useful -for sorting an Array of Buffers: - - var arr = [Buffer('1234'), Buffer('0123')]; - arr.sort(Buffer.compare); - - -### buf.length - -* Number - -The size of the buffer in bytes. Note that this is not necessarily the size -of the contents. `length` refers to the amount of memory allocated for the -buffer object. It does not change when the contents of the buffer are changed. - - buf = new Buffer(1234); - - console.log(buf.length); - buf.write("some string", 0, "ascii"); - console.log(buf.length); - - // 1234 - // 1234 - -While the `length` property is not immutable, changing the value of `length` -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 -use `buf.slice` to create a new buffer. - - buf = new Buffer(10); - buf.write("abcdefghj", 0, "ascii"); - console.log(buf.length); // 10 - buf = buf.slice(0,5); - console.log(buf.length); // 5 - -### buf.write(string[, offset][, length][, encoding]) - -* `string` String - data to be written to buffer -* `offset` Number, Optional, Default: 0 -* `length` Number, Optional, Default: `buffer.length - offset` -* `encoding` String, Optional, Default: 'utf8' - -Writes `string` to the buffer at `offset` using the given encoding. -`offset` defaults to `0`, `encoding` defaults to `'utf8'`. `length` is -the number of bytes to write. Returns number of octets written. If `buffer` did -not contain enough space to fit the entire string, it will write a partial -amount of the string. `length` defaults to `buffer.length - offset`. -The method will not write partial characters. - - buf = new Buffer(256); - len = buf.write('\u00bd + \u00bc = \u00be', 0); - console.log(len + " bytes: " + buf.toString('utf8', 0, len)); - -### buf.writeUIntLE(value, offset, byteLength[, noAssert]) -### buf.writeUIntBE(value, offset, byteLength[, noAssert]) -### buf.writeIntLE(value, offset, byteLength[, noAssert]) -### buf.writeIntBE(value, offset, byteLength[, noAssert]) - -* `value` {Number} Bytes to be written to buffer -* `offset` {Number} `0 <= offset <= buf.length` -* `byteLength` {Number} `0 < byteLength <= 6` -* `noAssert` {Boolean} Default: false -* Return: {Number} - -Writes `value` to the buffer at the specified `offset` and `byteLength`. -Supports up to 48 bits of accuracy. For example: - - var b = new Buffer(6); - b.writeUIntBE(0x1234567890ab, 0, 6); - // - -Set `noAssert` to `true` to skip validation of `value` and `offset`. Defaults -to `false`. - -### buf.readUIntLE(offset, byteLength[, noAssert]) -### buf.readUIntBE(offset, byteLength[, noAssert]) -### buf.readIntLE(offset, byteLength[, noAssert]) -### buf.readIntBE(offset, byteLength[, noAssert]) - -* `offset` {Number} `0 <= offset <= buf.length` -* `byteLength` {Number} `0 < byteLength <= 6` -* `noAssert` {Boolean} Default: false -* Return: {Number} - -A generalized version of all numeric read methods. Supports up to 48 bits of -accuracy. For example: - - var b = new Buffer(6); - b.writeUInt16LE(0x90ab, 0); - b.writeUInt32LE(0x12345678, 2); - b.readUIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits) - // output: '1234567890ab' - -Set `noAssert` to true to skip validation of `offset`. This means that `offset` -may be beyond the end of the buffer. Defaults to `false`. - -### buf.toString([encoding][, start][, end]) - -* `encoding` String, Optional, Default: 'utf8' -* `start` Number, Optional, Default: 0 -* `end` Number, Optional, Default: `buffer.length` +### Class Method: Buffer.isBuffer(obj) -Decodes and returns a string from buffer data encoded using the specified -character set encoding. If `encoding` is `undefined` or `null`, then `encoding` -defaults to `'utf8'`. The `start` and `end` parameters default to `0` and -`buffer.length` when `undefined`. +* `obj` Object +* Return: Boolean - buf = new Buffer(26); - for (var i = 0 ; i < 26 ; i++) { - buf[i] = i + 97; // 97 is ASCII a - } - buf.toString('ascii'); // outputs: abcdefghijklmnopqrstuvwxyz - buf.toString('ascii',0,5); // outputs: abcde - buf.toString('utf8',0,5); // outputs: abcde - buf.toString(undefined,0,5); // encoding defaults to 'utf8', outputs abcde +Tests if `obj` is a `Buffer`. -See `buffer.write()` example, above. +### Class Method: Buffer.isEncoding(encoding) +* `encoding` {String} The encoding string to test -### buf.toJSON() +Returns true if the `encoding` is a valid encoding argument, or false +otherwise. -Returns a JSON-representation of the Buffer instance. `JSON.stringify` -implicitly calls this function when stringifying a Buffer instance. +### buffer.entries() -Example: +Creates iterator for `[index, byte]` arrays. - var buf = new Buffer('test'); - var json = JSON.stringify(buf); +### buffer.keys() - console.log(json); - // '{"type":"Buffer","data":[116,101,115,116]}' +Creates iterator for buffer keys (indices). - var copy = JSON.parse(json, function(key, value) { - return value && value.type === 'Buffer' - ? new Buffer(value.data) - : value; - }); +### buffer.values() - console.log(copy); - // +Creates iterator for buffer values (bytes). This function is called automatically +when `buffer` is used in a `for..of` statement. ### buf[index] @@ -331,10 +209,6 @@ Example: copy an ASCII string into a buffer, one byte at a time: // Node.js -### buf.equals(otherBuffer) - -* `otherBuffer` {Buffer} - Returns a boolean of whether `this` and `otherBuffer` have the same bytes. @@ -388,35 +262,22 @@ region in the same buffer // efghijghijklmnopqrstuvwxyz +### buf.equals(otherBuffer) -### buf.slice([start[, end]]) - -* `start` Number, Optional, Default: 0 -* `end` Number, Optional, Default: `buffer.length` - -Returns a new buffer which references the same memory as the old, but offset -and cropped by the `start` (defaults to `0`) and `end` (defaults to -`buffer.length`) indexes. Negative indexes start from the end of the buffer. - -**Modifying the new buffer slice will modify memory in the original buffer!** - -Example: build a Buffer with the ASCII alphabet, take a slice, then modify one -byte from the original Buffer. - - var buf1 = new Buffer(26); +* `otherBuffer` {Buffer} - for (var i = 0 ; i < 26 ; i++) { - buf1[i] = i + 97; // 97 is ASCII a - } +### buf.fill(value[, offset][, end]) - var buf2 = buf1.slice(0, 3); - console.log(buf2.toString('ascii', 0, buf2.length)); - buf1[0] = 33; - console.log(buf2.toString('ascii', 0, buf2.length)); +* `value` +* `offset` Number, Optional +* `end` Number, Optional - // abc - // !bc +Fills the buffer with the specified value. If the `offset` (defaults to `0`) +and `end` (defaults to `buffer.length`) are not given it will fill the entire +buffer. + var b = new Buffer(50); + b.fill("h"); ### buf.indexOf(value[, byteOffset]) @@ -430,80 +291,73 @@ Accepts a String, Buffer or Number. 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 255. -### buf.readUInt8(offset[, noAssert]) - -* `offset` Number -* `noAssert` Boolean, Optional, Default: false -* Return: Number +### buf.length -Reads an unsigned 8 bit integer from the buffer at the specified offset. +* Number -Set `noAssert` to true to skip validation of `offset`. This means that `offset` -may be beyond the end of the buffer. Defaults to `false`. +The size of the buffer in bytes. Note that this is not necessarily the size +of the contents. `length` refers to the amount of memory allocated for the +buffer object. It does not change when the contents of the buffer are changed. -Example: + buf = new Buffer(1234); - var buf = new Buffer(4); + console.log(buf.length); + buf.write("some string", 0, "ascii"); + console.log(buf.length); - buf[0] = 0x3; - buf[1] = 0x4; - buf[2] = 0x23; - buf[3] = 0x42; + // 1234 + // 1234 - for (ii = 0; ii < buf.length; ii++) { - console.log(buf.readUInt8(ii)); - } +While the `length` property is not immutable, changing the value of `length` +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 +use `buf.slice` to create a new buffer. - // 0x3 - // 0x4 - // 0x23 - // 0x42 + buf = new Buffer(10); + buf.write("abcdefghj", 0, "ascii"); + console.log(buf.length); // 10 + buf = buf.slice(0,5); + console.log(buf.length); // 5 -### buf.readUInt16LE(offset[, noAssert]) -### buf.readUInt16BE(offset[, noAssert]) +### buf.readDoubleBE(offset[, noAssert]) +### buf.readDoubleLE(offset[, noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false * Return: Number -Reads an unsigned 16 bit integer from the buffer at the specified offset with -specified endian format. +Reads a 64 bit double from the buffer at the specified offset with specified +endian format. Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer. Defaults to `false`. Example: - var buf = new Buffer(4); + var buf = new Buffer(8); - buf[0] = 0x3; - buf[1] = 0x4; - buf[2] = 0x23; - buf[3] = 0x42; + buf[0] = 0x55; + buf[1] = 0x55; + buf[2] = 0x55; + buf[3] = 0x55; + buf[4] = 0x55; + buf[5] = 0x55; + buf[6] = 0xd5; + buf[7] = 0x3f; - console.log(buf.readUInt16BE(0)); - console.log(buf.readUInt16LE(0)); - console.log(buf.readUInt16BE(1)); - console.log(buf.readUInt16LE(1)); - console.log(buf.readUInt16BE(2)); - console.log(buf.readUInt16LE(2)); + console.log(buf.readDoubleLE(0)); - // 0x0304 - // 0x0403 - // 0x0423 - // 0x2304 - // 0x2342 - // 0x4223 + // 0.3333333333333333 -### buf.readUInt32LE(offset[, noAssert]) -### buf.readUInt32BE(offset[, noAssert]) +### buf.readFloatBE(offset[, noAssert]) +### buf.readFloatLE(offset[, noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false * Return: Number -Reads an unsigned 32 bit integer from the buffer at the specified offset with -specified endian format. +Reads a 32 bit float from the buffer at the specified offset with specified +endian format. Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer. Defaults to `false`. @@ -512,16 +366,14 @@ Example: var buf = new Buffer(4); - buf[0] = 0x3; - buf[1] = 0x4; - buf[2] = 0x23; - buf[3] = 0x42; + buf[0] = 0x00; + buf[1] = 0x00; + buf[2] = 0x80; + buf[3] = 0x3f; - console.log(buf.readUInt32BE(0)); - console.log(buf.readUInt32LE(0)); + console.log(buf.readFloatLE(0)); - // 0x03042342 - // 0x42230403 + // 0x01 ### buf.readInt8(offset[, noAssert]) @@ -537,8 +389,8 @@ may be beyond the end of the buffer. Defaults to `false`. Works as `buffer.readUInt8`, except buffer contents are treated as two's complement signed values. -### buf.readInt16LE(offset[, noAssert]) ### buf.readInt16BE(offset[, noAssert]) +### buf.readInt16LE(offset[, noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false @@ -553,8 +405,8 @@ may be beyond the end of the buffer. Defaults to `false`. Works as `buffer.readUInt16*`, except buffer contents are treated as two's complement signed values. -### buf.readInt32LE(offset[, noAssert]) ### buf.readInt32BE(offset[, noAssert]) +### buf.readInt32LE(offset[, noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false @@ -569,15 +421,33 @@ may be beyond the end of the buffer. Defaults to `false`. Works as `buffer.readUInt32*`, except buffer contents are treated as two's complement signed values. -### buf.readFloatLE(offset[, noAssert]) -### buf.readFloatBE(offset[, noAssert]) +### buf.readIntBE(offset, byteLength[, noAssert]) +### buf.readIntLE(offset, byteLength[, noAssert]) + +* `offset` {Number} `0 <= offset <= buf.length` +* `byteLength` {Number} `0 < byteLength <= 6` +* `noAssert` {Boolean} Default: false +* Return: {Number} + +A generalized version of all numeric read methods. Supports up to 48 bits of +accuracy. For example: + + var b = new Buffer(6); + b.writeUInt16LE(0x90ab, 0); + b.writeUInt32LE(0x12345678, 2); + b.readUIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits) + // output: '1234567890ab' + +Set `noAssert` to true to skip validation of `offset`. This means that `offset` +may be beyond the end of the buffer. Defaults to `false`. + +### buf.readUInt8(offset[, noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false * Return: Number -Reads a 32 bit float from the buffer at the specified offset with specified -endian format. +Reads an unsigned 8 bit integer from the buffer at the specified offset. Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer. Defaults to `false`. @@ -586,80 +456,201 @@ Example: var buf = new Buffer(4); - buf[0] = 0x00; - buf[1] = 0x00; - buf[2] = 0x80; - buf[3] = 0x3f; + buf[0] = 0x3; + buf[1] = 0x4; + buf[2] = 0x23; + buf[3] = 0x42; - console.log(buf.readFloatLE(0)); + for (ii = 0; ii < buf.length; ii++) { + console.log(buf.readUInt8(ii)); + } - // 0x01 + // 0x3 + // 0x4 + // 0x23 + // 0x42 -### buf.readDoubleLE(offset[, noAssert]) -### buf.readDoubleBE(offset[, noAssert]) +### buf.readUInt16BE(offset[, noAssert]) +### buf.readUInt16LE(offset[, noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false * Return: Number -Reads a 64 bit double from the buffer at the specified offset with specified -endian format. +Reads an unsigned 16 bit integer from the buffer at the specified offset with +specified endian format. Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer. Defaults to `false`. Example: - var buf = new Buffer(8); + var buf = new Buffer(4); - buf[0] = 0x55; - buf[1] = 0x55; - buf[2] = 0x55; - buf[3] = 0x55; - buf[4] = 0x55; - buf[5] = 0x55; - buf[6] = 0xd5; - buf[7] = 0x3f; + buf[0] = 0x3; + buf[1] = 0x4; + buf[2] = 0x23; + buf[3] = 0x42; - console.log(buf.readDoubleLE(0)); + console.log(buf.readUInt16BE(0)); + console.log(buf.readUInt16LE(0)); + console.log(buf.readUInt16BE(1)); + console.log(buf.readUInt16LE(1)); + console.log(buf.readUInt16BE(2)); + console.log(buf.readUInt16LE(2)); - // 0.3333333333333333 + // 0x0304 + // 0x0403 + // 0x0423 + // 0x2304 + // 0x2342 + // 0x4223 -### buf.writeUInt8(value, offset[, noAssert]) +### buf.readUInt32BE(offset[, noAssert]) +### buf.readUInt32LE(offset[, noAssert]) -* `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false +* Return: Number -Writes `value` to the buffer at the specified offset. Note, `value` must be a -valid unsigned 8 bit integer. +Reads an unsigned 32 bit integer from the buffer at the specified offset with +specified endian format. -Set `noAssert` to true to skip validation of `value` and `offset`. This means -that `value` may be too large for the specific function and `offset` may be -beyond the end of the buffer leading to the values being silently dropped. This -should not be used unless you are certain of correctness. Defaults to `false`. +Set `noAssert` to true to skip validation of `offset`. This means that `offset` +may be beyond the end of the buffer. Defaults to `false`. Example: var buf = new Buffer(4); - buf.writeUInt8(0x3, 0); - buf.writeUInt8(0x4, 1); - buf.writeUInt8(0x23, 2); - buf.writeUInt8(0x42, 3); - console.log(buf); + buf[0] = 0x3; + buf[1] = 0x4; + buf[2] = 0x23; + buf[3] = 0x42; - // + console.log(buf.readUInt32BE(0)); + console.log(buf.readUInt32LE(0)); -### buf.writeUInt16LE(value, offset[, noAssert]) -### buf.writeUInt16BE(value, offset[, noAssert]) + // 0x03042342 + // 0x42230403 + +### buf.readUIntBE(offset, byteLength[, noAssert]) +### buf.readUIntLE(offset, byteLength[, noAssert]) + +* `offset` {Number} `0 <= offset <= buf.length` +* `byteLength` {Number} `0 < byteLength <= 6` +* `noAssert` {Boolean} Default: false +* Return: {Number} + +A generalized version of all numeric read methods. Supports up to 48 bits of +accuracy. For example: + + var b = new Buffer(6); + b.writeUInt16LE(0x90ab, 0); + b.writeUInt32LE(0x12345678, 2); + b.readUIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits) + // output: '1234567890ab' + +### buf.slice([start[, end]]) + +* `start` Number, Optional, Default: 0 +* `end` Number, Optional, Default: `buffer.length` + +Returns a new buffer which references the same memory as the old, but offset +and cropped by the `start` (defaults to `0`) and `end` (defaults to +`buffer.length`) indexes. Negative indexes start from the end of the buffer. + +**Modifying the new buffer slice will modify memory in the original buffer!** + +Example: build a Buffer with the ASCII alphabet, take a slice, then modify one +byte from the original Buffer. + + var buf1 = new Buffer(26); + + for (var i = 0 ; i < 26 ; i++) { + buf1[i] = i + 97; // 97 is ASCII a + } + + var buf2 = buf1.slice(0, 3); + console.log(buf2.toString('ascii', 0, buf2.length)); + buf1[0] = 33; + console.log(buf2.toString('ascii', 0, buf2.length)); + + // abc + // !bc + +### buf.toString([encoding][, start][, end]) + +* `encoding` String, Optional, Default: 'utf8' +* `start` Number, Optional, Default: 0 +* `end` Number, Optional, Default: `buffer.length` + +Decodes and returns a string from buffer data encoded using the specified +character set encoding. If `encoding` is `undefined` or `null`, then `encoding` +defaults to `'utf8'`. The `start` and `end` parameters default to `0` and +`buffer.length` when `undefined`. + + buf = new Buffer(26); + for (var i = 0 ; i < 26 ; i++) { + buf[i] = i + 97; // 97 is ASCII a + } + buf.toString('ascii'); // outputs: abcdefghijklmnopqrstuvwxyz + buf.toString('ascii',0,5); // outputs: abcde + buf.toString('utf8',0,5); // outputs: abcde + buf.toString(undefined,0,5); // encoding defaults to 'utf8', outputs abcde + +See `buffer.write()` example, above. + + +### buf.toJSON() + +Returns a JSON-representation of the Buffer instance. `JSON.stringify` +implicitly calls this function when stringifying a Buffer instance. + +Example: + + var buf = new Buffer('test'); + var json = JSON.stringify(buf); + + console.log(json); + // '{"type":"Buffer","data":[116,101,115,116]}' + + var copy = JSON.parse(json, function(key, value) { + return value && value.type === 'Buffer' + ? new Buffer(value.data) + : value; + }); + + console.log(copy); + // + +### buf.write(string[, offset][, length][, encoding]) + +* `string` String - data to be written to buffer +* `offset` Number, Optional, Default: 0 +* `length` Number, Optional, Default: `buffer.length - offset` +* `encoding` String, Optional, Default: 'utf8' + +Writes `string` to the buffer at `offset` using the given encoding. +`offset` defaults to `0`, `encoding` defaults to `'utf8'`. `length` is +the number of bytes to write. Returns number of octets written. If `buffer` did +not contain enough space to fit the entire string, it will write a partial +amount of the string. `length` defaults to `buffer.length - offset`. +The method will not write partial characters. + + buf = new Buffer(256); + len = buf.write('\u00bd + \u00bc = \u00be', 0); + console.log(len + " bytes: " + buf.toString('utf8', 0, len)); + +### buf.writeDoubleBE(value, offset[, noAssert]) +### buf.writeDoubleLE(value, offset[, noAssert]) * `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false Writes `value` to the buffer at the specified offset with specified endian -format. Note, `value` must be a valid unsigned 16 bit integer. +format. Note, `value` must be a valid 64 bit double. Set `noAssert` to true to skip validation of `value` and `offset`. This means that `value` may be too large for the specific function and `offset` may be @@ -668,29 +659,27 @@ should not be used unless you are certain of correctness. Defaults to `false`. Example: - var buf = new Buffer(4); - buf.writeUInt16BE(0xdead, 0); - buf.writeUInt16BE(0xbeef, 2); + var buf = new Buffer(8); + buf.writeDoubleBE(0xdeadbeefcafebabe, 0); console.log(buf); - buf.writeUInt16LE(0xdead, 0); - buf.writeUInt16LE(0xbeef, 2); + buf.writeDoubleLE(0xdeadbeefcafebabe, 0); console.log(buf); - // - // + // + // -### buf.writeUInt32LE(value, offset[, noAssert]) -### buf.writeUInt32BE(value, offset[, noAssert]) +### buf.writeFloatBE(value, offset[, noAssert]) +### buf.writeFloatLE(value, offset[, noAssert]) * `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false Writes `value` to the buffer at the specified offset with specified endian -format. Note, `value` must be a valid unsigned 32 bit integer. +format. Note, behavior is unspecified if `value` is not a 32 bit float. Set `noAssert` to true to skip validation of `value` and `offset`. This means that `value` may be too large for the specific function and `offset` may be @@ -700,16 +689,16 @@ should not be used unless you are certain of correctness. Defaults to `false`. Example: var buf = new Buffer(4); - buf.writeUInt32BE(0xfeedface, 0); + buf.writeFloatBE(0xcafebabe, 0); console.log(buf); - buf.writeUInt32LE(0xfeedface, 0); + buf.writeFloatLE(0xcafebabe, 0); console.log(buf); - // - // + // + // ### buf.writeInt8(value, offset[, noAssert]) @@ -728,8 +717,8 @@ should not be used unless you are certain of correctness. Defaults to `false`. Works as `buffer.writeUInt8`, except value is written out as a two's complement signed integer into `buffer`. -### buf.writeInt16LE(value, offset[, noAssert]) ### buf.writeInt16BE(value, offset[, noAssert]) +### buf.writeInt16LE(value, offset[, noAssert]) * `value` Number * `offset` Number @@ -746,8 +735,8 @@ should not be used unless you are certain of correctness. Defaults to `false`. Works as `buffer.writeUInt16*`, except value is written out as a two's complement signed integer into `buffer`. -### buf.writeInt32LE(value, offset[, noAssert]) ### buf.writeInt32BE(value, offset[, noAssert]) +### buf.writeInt32LE(value, offset[, noAssert]) * `value` Number * `offset` Number @@ -764,15 +753,33 @@ should not be used unless you are certain of correctness. Defaults to `false`. Works as `buffer.writeUInt32*`, except value is written out as a two's complement signed integer into `buffer`. -### buf.writeFloatLE(value, offset[, noAssert]) -### buf.writeFloatBE(value, offset[, noAssert]) +### buf.writeIntBE(value, offset, byteLength[, noAssert]) +### buf.writeIntLE(value, offset, byteLength[, noAssert]) + +* `value` {Number} Bytes to be written to buffer +* `offset` {Number} `0 <= offset <= buf.length` +* `byteLength` {Number} `0 < byteLength <= 6` +* `noAssert` {Boolean} Default: false +* Return: {Number} + +Writes `value` to the buffer at the specified `offset` and `byteLength`. +Supports up to 48 bits of accuracy. For example: + + var b = new Buffer(6); + b.writeUIntBE(0x1234567890ab, 0, 6); + // + +Set `noAssert` to `true` to skip validation of `value` and `offset`. Defaults +to `false`. + +### buf.writeUInt8(value, offset[, noAssert]) * `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false -Writes `value` to the buffer at the specified offset with specified endian -format. Note, behavior is unspecified if `value` is not a 32 bit float. +Writes `value` to the buffer at the specified offset. Note, `value` must be a +valid unsigned 8 bit integer. Set `noAssert` to true to skip validation of `value` and `offset`. This means that `value` may be too large for the specific function and `offset` may be @@ -782,26 +789,24 @@ should not be used unless you are certain of correctness. Defaults to `false`. Example: var buf = new Buffer(4); - buf.writeFloatBE(0xcafebabe, 0); - - console.log(buf); - - buf.writeFloatLE(0xcafebabe, 0); + buf.writeUInt8(0x3, 0); + buf.writeUInt8(0x4, 1); + buf.writeUInt8(0x23, 2); + buf.writeUInt8(0x42, 3); console.log(buf); - // - // + // -### buf.writeDoubleLE(value, offset[, noAssert]) -### buf.writeDoubleBE(value, offset[, noAssert]) +### buf.writeUInt16BE(value, offset[, noAssert]) +### buf.writeUInt16LE(value, offset[, noAssert]) * `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false Writes `value` to the buffer at the specified offset with specified endian -format. Note, `value` must be a valid 64 bit double. +format. Note, `value` must be a valid unsigned 16 bit integer. Set `noAssert` to true to skip validation of `value` and `offset`. This means that `value` may be too large for the specific function and `offset` may be @@ -810,43 +815,67 @@ should not be used unless you are certain of correctness. Defaults to `false`. Example: - var buf = new Buffer(8); - buf.writeDoubleBE(0xdeadbeefcafebabe, 0); + var buf = new Buffer(4); + buf.writeUInt16BE(0xdead, 0); + buf.writeUInt16BE(0xbeef, 2); console.log(buf); - buf.writeDoubleLE(0xdeadbeefcafebabe, 0); + buf.writeUInt16LE(0xdead, 0); + buf.writeUInt16LE(0xbeef, 2); console.log(buf); - // - // + // + // -### buf.fill(value[, offset][, end]) +### buf.writeUInt32BE(value, offset[, noAssert]) +### buf.writeUInt32LE(value, offset[, noAssert]) -* `value` -* `offset` Number, Optional -* `end` Number, Optional +* `value` Number +* `offset` Number +* `noAssert` Boolean, Optional, Default: false -Fills the buffer with the specified value. If the `offset` (defaults to `0`) -and `end` (defaults to `buffer.length`) are not given it will fill the entire -buffer. +Writes `value` to the buffer at the specified offset with specified endian +format. Note, `value` must be a valid unsigned 32 bit integer. - var b = new Buffer(50); - b.fill("h"); +Set `noAssert` to true to skip validation of `value` and `offset`. This means +that `value` may be too large for the specific function and `offset` may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to `false`. -### buffer.values() +Example: -Creates iterator for buffer values (bytes). This function is called automatically -when `buffer` is used in a `for..of` statement. + var buf = new Buffer(4); + buf.writeUInt32BE(0xfeedface, 0); -### buffer.keys() + console.log(buf); -Creates iterator for buffer keys (indices). + buf.writeUInt32LE(0xfeedface, 0); -### buffer.entries() + console.log(buf); -Creates iterator for `[index, byte]` arrays. + // + // + +### buf.writeUIntBE(value, offset, byteLength[, noAssert]) +### buf.writeUIntLE(value, offset, byteLength[, noAssert]) + +* `value` {Number} Bytes to be written to buffer +* `offset` {Number} `0 <= offset <= buf.length` +* `byteLength` {Number} `0 < byteLength <= 6` +* `noAssert` {Boolean} Default: false +* Return: {Number} + +Writes `value` to the buffer at the specified `offset` and `byteLength`. +Supports up to 48 bits of accuracy. For example: + + var b = new Buffer(6); + b.writeUIntBE(0x1234567890ab, 0, 6); + // + +Set `noAssert` to `true` to skip validation of `value` and `offset`. Defaults +to `false`. ## buffer.INSPECT_MAX_BYTES From 7b4f78a6014ac6e370b17fe233b30f7804824725 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 10:50:18 -0500 Subject: [PATCH 03/32] doc: sort child_process alphabetically Reorders, with no contextual changes, the child_process documentation alphabetically. --- doc/api/child_process.markdown | 598 ++++++++++++++++----------------- 1 file changed, 299 insertions(+), 299 deletions(-) diff --git a/doc/api/child_process.markdown b/doc/api/child_process.markdown index 954354cc32a810..ad7ceeb9612dca 100644 --- a/doc/api/child_process.markdown +++ b/doc/api/child_process.markdown @@ -31,6 +31,22 @@ The ChildProcess class is not intended to be used directly. Use the `spawn()`, `exec()`, `execFile()`, or `fork()` methods to create a Child Process instance. +### Event: 'close' + +* `code` {Number} the exit code, if it exited normally. +* `signal` {String} the signal passed to kill the child process, if it + was killed by the parent. + +This event is emitted when the stdio streams of a child process have all +terminated. This is distinct from 'exit', since multiple processes +might share the same stdio streams. + +### Event: 'disconnect' + +This event is emitted after calling the `.disconnect()` method in the parent +or in the child. After disconnecting it is no longer possible to send messages, +and the `.connected` property is false. + ### Event: 'error' * `err` {Error Object} the error. @@ -67,22 +83,6 @@ it will exit. See `waitpid(2)`. -### Event: 'close' - -* `code` {Number} the exit code, if it exited normally. -* `signal` {String} the signal passed to kill the child process, if it - was killed by the parent. - -This event is emitted when the stdio streams of a child process have all -terminated. This is distinct from 'exit', since multiple processes -might share the same stdio streams. - -### Event: 'disconnect' - -This event is emitted after calling the `.disconnect()` method in the parent -or in the child. After disconnecting it is no longer possible to send messages, -and the `.connected` property is false. - ### Event: 'message' * `message` {Object} a parsed JSON object or primitive value. @@ -92,99 +92,24 @@ and the `.connected` property is false. Messages sent by `.send(message, [sendHandle])` are obtained using the `message` event. -### child.stdin - -* {Stream object} - -A `Writable Stream` that represents the child process's `stdin`. -If the child is waiting to read all its input, it will not continue until this -stream has been closed via `end()`. - -If the child was not spawned with `stdio[0]` set to `'pipe'`, then this will -not be set. - -`child.stdin` is shorthand for `child.stdio[0]`. Both properties will refer -to the same object, or null. - -### child.stdout - -* {Stream object} - -A `Readable Stream` that represents the child process's `stdout`. - -If the child was not spawned with `stdio[1]` set to `'pipe'`, then this will -not be set. - -`child.stdout` is shorthand for `child.stdio[1]`. Both properties will refer -to the same object, or null. - -### child.stderr - -* {Stream object} - -A `Readable Stream` that represents the child process's `stderr`. - -If the child was not spawned with `stdio[2]` set to `'pipe'`, then this will -not be set. - -`child.stderr` is shorthand for `child.stdio[2]`. Both properties will refer -to the same object, or null. - -### child.stdio - -* {Array} - -A sparse array of pipes to the child process, corresponding with positions in -the [stdio](#child_process_options_stdio) option to -[spawn](#child_process_child_process_spawn_command_args_options) that have been -set to `'pipe'`. -Note that streams 0-2 are also available as ChildProcess.stdin, -ChildProcess.stdout, and ChildProcess.stderr, respectively. - -In the following example, only the child's fd `1` is setup as a pipe, so only -the parent's `child.stdio[1]` is a stream, all other values in the array are -`null`. - - var assert = require('assert'); - var fs = require('fs'); - var child_process = require('child_process'); - - child = child_process.spawn('ls', { - stdio: [ - 0, // use parents stdin for child - 'pipe', // pipe child's stdout to parent - fs.openSync('err.out', 'w') // direct child's stderr to a file - ] - }); - - assert.equal(child.stdio[0], null); - assert.equal(child.stdio[0], child.stdin); - - assert(child.stdout); - assert.equal(child.stdio[1], child.stdout); - - assert.equal(child.stdio[2], null); - assert.equal(child.stdio[2], child.stderr); - -### child.pid - -* {Integer} - -The PID of the child process. +### child.connected -Example: +* {Boolean} Set to false after `.disconnect` is called - var spawn = require('child_process').spawn, - grep = spawn('grep', ['ssh']); +If `.connected` is false, it is no longer possible to send messages. - console.log('Spawned child pid: ' + grep.pid); - grep.stdin.end(); +### child.disconnect() -### child.connected +Close the IPC channel between parent and child, allowing the child to exit +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 +child, and it is no longer possible to send messages. -* {Boolean} Set to false after `.disconnect` is called +The 'disconnect' event will be emitted when there are no messages in the process +of being received, most likely immediately. -If `.connected` is false, it is no longer possible to send messages. +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.kill([signal]) @@ -215,6 +140,20 @@ to a process. See `kill(2)` +### child.pid + +* {Integer} + +The PID of the child process. + +Example: + + var spawn = require('child_process').spawn, + grep = spawn('grep', ['ssh']); + + console.log('Spawned child pid: ' + grep.pid); + grep.stdin.end(); + ### child.send(message[, sendHandle][, callback]) * `message` {Object} @@ -340,23 +279,206 @@ longer keep track of when the socket is destroyed. To indicate this condition the `.connections` property becomes `null`. It is also recommended not to use `.maxConnections` in this condition. -### child.disconnect() +### child.stderr -Close the IPC channel between parent and child, allowing the child to exit -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 -child, and it is no longer possible to send messages. +* {Stream object} -The 'disconnect' event will be emitted when there are no messages in the process -of being received, most likely immediately. +A `Readable Stream` that represents the child process's `stderr`. -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()`). +If the child was not spawned with `stdio[2]` set to `'pipe'`, then this will +not be set. + +`child.stderr` is shorthand for `child.stdio[2]`. Both properties will refer +to the same object, or null. + +### child.stdin + +* {Stream object} + +A `Writable Stream` that represents the child process's `stdin`. +If the child is waiting to read all its input, it will not continue until this +stream has been closed via `end()`. + +If the child was not spawned with `stdio[0]` set to `'pipe'`, then this will +not be set. + +`child.stdin` is shorthand for `child.stdio[0]`. Both properties will refer +to the same object, or null. + +### child.stdio + +* {Array} + +A sparse array of pipes to the child process, corresponding with positions in +the [stdio](#child_process_options_stdio) option to +[spawn](#child_process_child_process_spawn_command_args_options) that have been +set to `'pipe'`. +Note that streams 0-2 are also available as ChildProcess.stdin, +ChildProcess.stdout, and ChildProcess.stderr, respectively. + +In the following example, only the child's fd `1` is setup as a pipe, so only +the parent's `child.stdio[1]` is a stream, all other values in the array are +`null`. + + var assert = require('assert'); + var fs = require('fs'); + var child_process = require('child_process'); + + child = child_process.spawn('ls', { + stdio: [ + 0, // use parents stdin for child + 'pipe', // pipe child's stdout to parent + fs.openSync('err.out', 'w') // direct child's stderr to a file + ] + }); + + assert.equal(child.stdio[0], null); + assert.equal(child.stdio[0], child.stdin); + + assert(child.stdout); + assert.equal(child.stdio[1], child.stdout); + + assert.equal(child.stdio[2], null); + assert.equal(child.stdio[2], child.stderr); + +### child.stdout + +* {Stream object} + +A `Readable Stream` that represents the child process's `stdout`. + +If the child was not spawned with `stdio[1]` set to `'pipe'`, then this will +not be set. + +`child.stdout` is shorthand for `child.stdio[1]`. Both properties will refer +to the same object, or null. ## Asynchronous Process Creation -These methods follow the common async programming patterns (accepting a -callback or returning an EventEmitter). +These methods follow the common async programming patterns (accepting a +callback or returning an EventEmitter). + +### child_process.exec(command[, options], callback) + +* `command` {String} The command to run, with space-separated arguments +* `options` {Object} + * `cwd` {String} Current working directory of the child process + * `env` {Object} Environment key-value pairs + * `encoding` {String} (Default: 'utf8') + * `shell` {String} Shell to execute the command with + (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should + understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows, + command line parsing should be compatible with `cmd.exe`.) + * `timeout` {Number} (Default: 0) + * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or + stderr - if exceeded child process is killed (Default: `200*1024`) + * `killSignal` {String} (Default: 'SIGTERM') + * `uid` {Number} Sets the user identity of the process. (See setuid(2).) + * `gid` {Number} Sets the group identity of the process. (See setgid(2).) +* `callback` {Function} called with the output when process terminates + * `error` {Error} + * `stdout` {Buffer} + * `stderr` {Buffer} +* Return: ChildProcess object + +Runs a command in a shell and buffers the output. + + var exec = require('child_process').exec, + child; + + child = exec('cat *.js bad_file | wc -l', + function (error, stdout, stderr) { + console.log('stdout: ' + stdout); + console.log('stderr: ' + stderr); + if (error !== null) { + console.log('exec error: ' + 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 the exit code of the child process, and `error.signal` will be set to the +signal that terminated the process. + +There is a second optional argument to specify several options. The +default options are + + { encoding: 'utf8', + timeout: 0, + maxBuffer: 200*1024, + killSignal: 'SIGTERM', + cwd: null, + env: null } + +If `timeout` is greater than 0, then it will kill the child process +if it runs longer than `timeout` milliseconds. The child process is killed with +`killSignal` (default: `'SIGTERM'`). `maxBuffer` specifies the largest +amount of data (in bytes) allowed on stdout or stderr - if this value is +exceeded then the child process is killed. + +*Note: Unlike the `exec()` POSIX system call, `child_process.exec()` does not replace +the existing process and uses a shell to execute the command.* + +### child_process.execFile(file[, args][, options][, callback]) + +* `file` {String} The filename of the program to run +* `args` {Array} List of string arguments +* `options` {Object} + * `cwd` {String} Current working directory of the child process + * `env` {Object} Environment key-value pairs + * `encoding` {String} (Default: 'utf8') + * `timeout` {Number} (Default: 0) + * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or + stderr - if exceeded child process is killed (Default: 200\*1024) + * `killSignal` {String} (Default: 'SIGTERM') + * `uid` {Number} Sets the user identity of the process. (See setuid(2).) + * `gid` {Number} Sets the group identity of the process. (See setgid(2).) +* `callback` {Function} called with the output when process terminates + * `error` {Error} + * `stdout` {Buffer} + * `stderr` {Buffer} +* Return: ChildProcess object + +This is similar to [`child_process.exec()`](#child_process_child_process_exec_command_options_callback) except it does not execute a +subshell but rather the specified file directly. This makes it slightly +leaner than [`child_process.exec()`](#child_process_child_process_exec_command_options_callback). It has the same options. + + +### child_process.fork(modulePath[, args][, options]) + +* `modulePath` {String} The module to run in the child +* `args` {Array} List of string arguments +* `options` {Object} + * `cwd` {String} Current working directory of the child process + * `env` {Object} Environment key-value pairs + * `execPath` {String} Executable used to create the child process + * `execArgv` {Array} List of string arguments passed to the executable + (Default: `process.execArgv`) + * `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 + the "pipe" and "inherit" options for `spawn()`'s `stdio` for more details + (default is false) + * `uid` {Number} Sets the user identity of the process. (See setuid(2).) + * `gid` {Number} Sets the group identity of the process. (See setgid(2).) +* Return: ChildProcess object + +This is a special case of the [`child_process.spawn()`](#child_process_child_process_spawn_command_args_options) functionality for spawning Node.js +processes. In addition to having all the methods in a normal ChildProcess +instance, the returned object has a communication channel built-in. See +[`child.send(message, [sendHandle])`](#child_process_child_send_message_sendhandle_callback) for details. + +These child Node.js processes are still whole new instances of V8. Assume at +least 30ms startup and 10mb memory for each new Node.js. That is, you cannot +create many thousands of them. + +The `execPath` property in the `options` object allows for a process to be +created for the child rather than the current `node` executable. This should be +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 +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 +current process.* ### child_process.spawn(command[, args][, options]) @@ -452,6 +574,42 @@ Example of checking for failed exec: console.log('Failed to start child process.'); }); +#### options.detached + +On Windows, this makes it possible for the child to continue running after the +parent exits. The child will have a new console window (this cannot be +disabled). + +On non-Windows, if the `detached` option is set, the child process will be made +the leader of a new process group and session. Note that child processes may +continue running after the parent exits whether they are detached or not. See +`setsid(2)` for more information. + +By default, the parent will wait for the detached child to exit. To prevent +the parent from waiting for a given `child`, use the `child.unref()` method, +and the parent's event loop will not include the child in its reference count. + +Example of detaching a long-running process and redirecting its output to a +file: + + var fs = require('fs'), + spawn = require('child_process').spawn, + out = fs.openSync('./out.log', 'a'), + err = fs.openSync('./out.log', 'a'); + + var child = spawn('prg', [], { + detached: true, + stdio: [ 'ignore', out, err ] + }); + + child.unref(); + +When using the `detached` option to start a long-running process, the process +will not stay running in the background after the parent exits unless it is +provided with a `stdio` configuration that is not connected to the parent. +If the parent's `stdio` is inherited, the child will remain attached to the +controlling terminal. + #### options.stdio As a shorthand, the `stdio` argument may be one of the following strings: @@ -505,166 +663,8 @@ Example: // startd-style interface. spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] }); -#### options.detached - -On Windows, this makes it possible for the child to continue running after the -parent exits. The child will have a new console window (this cannot be -disabled). - -On non-Windows, if the `detached` option is set, the child process will be made -the leader of a new process group and session. Note that child processes may -continue running after the parent exits whether they are detached or not. See -`setsid(2)` for more information. - -By default, the parent will wait for the detached child to exit. To prevent -the parent from waiting for a given `child`, use the `child.unref()` method, -and the parent's event loop will not include the child in its reference count. - -Example of detaching a long-running process and redirecting its output to a -file: - - var fs = require('fs'), - spawn = require('child_process').spawn, - out = fs.openSync('./out.log', 'a'), - err = fs.openSync('./out.log', 'a'); - - var child = spawn('prg', [], { - detached: true, - stdio: [ 'ignore', out, err ] - }); - - child.unref(); - -When using the `detached` option to start a long-running process, the process -will not stay running in the background after the parent exits unless it is -provided with a `stdio` configuration that is not connected to the parent. -If the parent's `stdio` is inherited, the child will remain attached to the -controlling terminal. - See also: [`child_process.exec()`](#child_process_child_process_exec_command_options_callback) and [`child_process.fork()`](#child_process_child_process_fork_modulepath_args_options) -### child_process.exec(command[, options], callback) - -* `command` {String} The command to run, with space-separated arguments -* `options` {Object} - * `cwd` {String} Current working directory of the child process - * `env` {Object} Environment key-value pairs - * `encoding` {String} (Default: 'utf8') - * `shell` {String} Shell to execute the command with - (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should - understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows, - command line parsing should be compatible with `cmd.exe`.) - * `timeout` {Number} (Default: 0) - * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or - stderr - if exceeded child process is killed (Default: `200*1024`) - * `killSignal` {String} (Default: 'SIGTERM') - * `uid` {Number} Sets the user identity of the process. (See setuid(2).) - * `gid` {Number} Sets the group identity of the process. (See setgid(2).) -* `callback` {Function} called with the output when process terminates - * `error` {Error} - * `stdout` {Buffer} - * `stderr` {Buffer} -* Return: ChildProcess object - -Runs a command in a shell and buffers the output. - - var exec = require('child_process').exec, - child; - - child = exec('cat *.js bad_file | wc -l', - function (error, stdout, stderr) { - console.log('stdout: ' + stdout); - console.log('stderr: ' + stderr); - if (error !== null) { - console.log('exec error: ' + 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 the exit code of the child process, and `error.signal` will be set to the -signal that terminated the process. - -There is a second optional argument to specify several options. The -default options are - - { encoding: 'utf8', - timeout: 0, - maxBuffer: 200*1024, - killSignal: 'SIGTERM', - cwd: null, - env: null } - -If `timeout` is greater than 0, then it will kill the child process -if it runs longer than `timeout` milliseconds. The child process is killed with -`killSignal` (default: `'SIGTERM'`). `maxBuffer` specifies the largest -amount of data (in bytes) allowed on stdout or stderr - if this value is -exceeded then the child process is killed. - -*Note: Unlike the `exec()` POSIX system call, `child_process.exec()` does not replace -the existing process and uses a shell to execute the command.* - -### child_process.execFile(file[, args][, options][, callback]) - -* `file` {String} The filename of the program to run -* `args` {Array} List of string arguments -* `options` {Object} - * `cwd` {String} Current working directory of the child process - * `env` {Object} Environment key-value pairs - * `encoding` {String} (Default: 'utf8') - * `timeout` {Number} (Default: 0) - * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or - stderr - if exceeded child process is killed (Default: 200\*1024) - * `killSignal` {String} (Default: 'SIGTERM') - * `uid` {Number} Sets the user identity of the process. (See setuid(2).) - * `gid` {Number} Sets the group identity of the process. (See setgid(2).) -* `callback` {Function} called with the output when process terminates - * `error` {Error} - * `stdout` {Buffer} - * `stderr` {Buffer} -* Return: ChildProcess object - -This is similar to [`child_process.exec()`](#child_process_child_process_exec_command_options_callback) except it does not execute a -subshell but rather the specified file directly. This makes it slightly -leaner than [`child_process.exec()`](#child_process_child_process_exec_command_options_callback). It has the same options. - - -### child_process.fork(modulePath[, args][, options]) - -* `modulePath` {String} The module to run in the child -* `args` {Array} List of string arguments -* `options` {Object} - * `cwd` {String} Current working directory of the child process - * `env` {Object} Environment key-value pairs - * `execPath` {String} Executable used to create the child process - * `execArgv` {Array} List of string arguments passed to the executable - (Default: `process.execArgv`) - * `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 - the "pipe" and "inherit" options for `spawn()`'s `stdio` for more details - (default is false) - * `uid` {Number} Sets the user identity of the process. (See setuid(2).) - * `gid` {Number} Sets the group identity of the process. (See setgid(2).) -* Return: ChildProcess object - -This is a special case of the [`child_process.spawn()`](#child_process_child_process_spawn_command_args_options) functionality for spawning Node.js -processes. In addition to having all the methods in a normal ChildProcess -instance, the returned object has a communication channel built-in. See -[`child.send(message, [sendHandle])`](#child_process_child_send_message_sendhandle_callback) for details. - -These child Node.js processes are still whole new instances of V8. Assume at -least 30ms startup and 10mb memory for each new Node.js. That is, you cannot -create many thousands of them. - -The `execPath` property in the `options` object allows for a process to be -created for the child rather than the current `node` executable. This should be -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 -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 -current process.* - ## Synchronous Process Creation These methods are **synchronous**, meaning they **WILL** block the event loop, @@ -674,15 +674,17 @@ Blocking calls like these are mostly useful for simplifying general purpose scripting tasks and for simplifying the loading/processing of application configuration at startup. -### child_process.spawnSync(command[, args][, options]) +### child_process.execFileSync(file[, args][, options]) -* `command` {String} The command to run +* `file` {String} The filename of the program to run * `args` {Array} List of string arguments * `options` {Object} * `cwd` {String} Current working directory of the child process * `input` {String|Buffer} The value which will be passed as stdin to the spawned process - supplying this value will override `stdio[0]` - * `stdio` {Array} Child's stdio configuration. + * `stdio` {Array} Child's stdio configuration. (Default: 'pipe') + - `stderr` by default will be output to the parent process' stderr unless + `stdio` is specified * `env` {Object} Environment key-value pairs * `uid` {Number} Sets the user identity of the process. (See setuid(2).) * `gid` {Number} Sets the group identity of the process. (See setgid(2).) @@ -691,21 +693,22 @@ configuration at startup. * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed * `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer') -* return: {Object} - * `pid` {Number} Pid of the child process - * `output` {Array} Array of results from stdio output - * `stdout` {Buffer|String} The contents of `output[1]` - * `stderr` {Buffer|String} The contents of `output[2]` - * `status` {Number} The exit code of the child process - * `signal` {String} The signal used to kill the child process - * `error` {Error} The error object if the child process failed or timed out +* return: {Buffer|String} The stdout from the command -`spawnSync` will not return until the child process has fully closed. When a +`execFileSync` will not return until the child process has fully closed. When a timeout has been encountered and `killSignal` is sent, the method won't return 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 process has exited. +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 +[`child_process.spawnSync()`](#child_process_child_process_spawnsync_command_args_options) + +[EventEmitter]: events.html#events_class_events_eventemitter +[net.Server]: net.html#net_class_net_server +[net.Socket]: net.html#net_class_net_socket + ### child_process.execSync(command[, options]) * `command` {String} The command to run @@ -740,17 +743,15 @@ 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 [`child_process.spawnSync()`](#child_process_child_process_spawnsync_command_args_options) -### child_process.execFileSync(file[, args][, options]) +### child_process.spawnSync(command[, args][, options]) -* `file` {String} The filename of the program to run +* `command` {String} The command to run * `args` {Array} List of string arguments * `options` {Object} * `cwd` {String} Current working directory of the child process * `input` {String|Buffer} The value which will be passed as stdin to the spawned process - supplying this value will override `stdio[0]` - * `stdio` {Array} Child's stdio configuration. (Default: 'pipe') - - `stderr` by default will be output to the parent process' stderr unless - `stdio` is specified + * `stdio` {Array} Child's stdio configuration. * `env` {Object} Environment key-value pairs * `uid` {Number} Sets the user identity of the process. (See setuid(2).) * `gid` {Number} Sets the group identity of the process. (See setgid(2).) @@ -759,18 +760,17 @@ throw. The `Error` object will contain the entire result from * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed * `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer') -* return: {Buffer|String} The stdout from the command +* return: {Object} + * `pid` {Number} Pid of the child process + * `output` {Array} Array of results from stdio output + * `stdout` {Buffer|String} The contents of `output[1]` + * `stderr` {Buffer|String} The contents of `output[2]` + * `status` {Number} The exit code of the child process + * `signal` {String} The signal used to kill the child process + * `error` {Error} The error object if the child process failed or timed out -`execFileSync` will not return until the child process has fully closed. When a +`spawnSync` will not return until the child process has fully closed. When a timeout has been encountered and `killSignal` is sent, the method won't return 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 process has exited. - -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 -[`child_process.spawnSync()`](#child_process_child_process_spawnsync_command_args_options) - -[EventEmitter]: events.html#events_class_events_eventemitter -[net.Server]: net.html#net_class_net_server -[net.Socket]: net.html#net_class_net_socket From e650680267e5eee4cacebee5d6dbf58a3473dd10 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 10:51:00 -0500 Subject: [PATCH 04/32] doc: sort cluster alphabetically Reorders, with no contextual changes, the cluster documentation alphabetically. --- doc/api/cluster.markdown | 748 ++++++++++++++++++++------------------- 1 file changed, 375 insertions(+), 373 deletions(-) diff --git a/doc/api/cluster.markdown b/doc/api/cluster.markdown index a1d30ef6001b8b..594dea0832908d 100644 --- a/doc/api/cluster.markdown +++ b/doc/api/cluster.markdown @@ -101,294 +101,219 @@ will be dropped and new connections will be refused. Node.js does not automatically manage the number of workers for you, however. It is your responsibility to manage the worker pool for your application's needs. -## cluster.schedulingPolicy - -The scheduling policy, either `cluster.SCHED_RR` for round-robin or -`cluster.SCHED_NONE` to leave it to the operating system. This is a -global setting and effectively frozen once you spawn the first worker -or call `cluster.setupMaster()`, whatever comes first. - -`SCHED_RR` is the default on all operating systems except Windows. -Windows will change to `SCHED_RR` once libuv is able to effectively -distribute IOCP handles without incurring a large performance hit. - -`cluster.schedulingPolicy` can also be set through the -`NODE_CLUSTER_SCHED_POLICY` environment variable. Valid -values are `"rr"` and `"none"`. - -## cluster.settings - -* {Object} - * `execArgv` {Array} list of string arguments passed to the Node.js - executable. (Default=`process.execArgv`) - * `exec` {String} file path to worker file. (Default=`process.argv[1]`) - * `args` {Array} string arguments passed to worker. - (Default=`process.argv.slice(2)`) - * `silent` {Boolean} whether or not to send output to parent's stdio. - (Default=`false`) - * `uid` {Number} Sets the user identity of the process. (See setuid(2).) - * `gid` {Number} Sets the group identity of the process. (See setgid(2).) - -After calling `.setupMaster()` (or `.fork()`) this settings object will contain -the settings, including the default values. - -It is effectively frozen after being set, because `.setupMaster()` can -only be called once. - -This object is not supposed to be changed or set manually, by you. - -## cluster.isMaster - -* {Boolean} -True if the process is a master. This is determined -by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` is -undefined, then `isMaster` is `true`. - -## cluster.isWorker - -* {Boolean} -True if the process is not a master (it is the negation of `cluster.isMaster`). - -## Event: 'fork' +## Class: Worker -* `worker` {Worker object} +A Worker object contains all public information and method about a worker. +In the master it can be obtained using `cluster.workers`. In a worker +it can be obtained using `cluster.worker`. -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. +### Event: 'disconnect' - var timeouts = []; - function errorMsg() { - console.error("Something must be wrong with the connection ..."); - } +Similar to the `cluster.on('disconnect')` event, but specific to this worker. - cluster.on('fork', function(worker) { - timeouts[worker.id] = setTimeout(errorMsg, 2000); - }); - cluster.on('listening', function(worker, address) { - clearTimeout(timeouts[worker.id]); - }); - cluster.on('exit', function(worker, code, signal) { - clearTimeout(timeouts[worker.id]); - errorMsg(); + cluster.fork().on('disconnect', function() { + // Worker has disconnected }); -## Event: 'online' - -* `worker` {Worker object} +### Event: 'error' -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. -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. +This event is the same as the one provided by `child_process.fork()`. - cluster.on('online', function(worker) { - console.log("Yay, the worker responded after it was forked"); - }); +In a worker you can also use `process.on('error')`. -## Event: 'listening' +[ChildProcess.send()]: child_process.html#child_process_child_send_message_sendhandle_callback -* `worker` {Worker object} -* `address` {Object} +### Event: 'exit' -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. +* `code` {Number} the exit code, if it exited normally. +* `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused + the process to be killed. -The event handler is executed with two arguments, the `worker` contains the worker -object and the `address` object contains the following connection properties: -`address`, `port` and `addressType`. This is very useful if the worker is listening -on more than one address. +Similar to the `cluster.on('exit')` event, but specific to this worker. - cluster.on('listening', function(worker, address) { - console.log("A worker is now connected to " + address.address + ":" + address.port); + var worker = cluster.fork(); + worker.on('exit', function(code, signal) { + if( signal ) { + console.log("worker was killed by signal: "+signal); + } else if( code !== 0 ) { + console.log("worker exited with error code: "+code); + } else { + console.log("worker success!"); + } }); -The `addressType` is one of: - -* `4` (TCPv4) -* `6` (TCPv6) -* `-1` (unix domain socket) -* `"udp4"` or `"udp6"` (UDP v4 or v6) - -## Event: 'disconnect' - -* `worker` {Worker object} +### Event: 'listening' -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.disconnect()). +* `address` {Object} -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 -long-living connections. +Similar to the `cluster.on('listening')` event, but specific to this worker. - cluster.on('disconnect', function(worker) { - console.log('The worker #' + worker.id + ' has disconnected'); + cluster.fork().on('listening', function(address) { + // Worker is listening }); -## Event: 'exit' - -* `worker` {Worker object} -* `code` {Number} the exit code, if it exited normally. -* `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused - the process to be killed. - -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. +It is not emitted in the worker. - cluster.on('exit', function(worker, code, signal) { - console.log('worker %d died (%s). restarting...', - worker.process.pid, signal || code); - cluster.fork(); - }); +### Event: 'message' -See [child_process event: 'exit'](child_process.html#child_process_event_exit). +* `message` {Object} -## Event: 'message' +Similar to the `cluster.on('message')` event, but specific to this worker. -* `worker` {Worker object} -* `message` {Object} +This event is the same as the one provided by `child_process.fork()`. -Emitted when any worker receives a message. +In a worker you can also use `process.on('message')`. -See -[child_process event: 'message'](child_process.html#child_process_event_message). +As an example, here is a cluster that keeps count of the number of requests +in the master process using the message system: -## Event: 'setup' + var cluster = require('cluster'); + var http = require('http'); -* `settings` {Object} + if (cluster.isMaster) { -Emitted every time `.setupMaster()` is called. + // Keep track of http requests + var numReqs = 0; + setInterval(function() { + console.log("numReqs =", numReqs); + }, 1000); -The `settings` object is the `cluster.settings` object at the time -`.setupMaster()` was called and is advisory only, since multiple calls to -`.setupMaster()` can be made in a single tick. + // Count requests + function messageHandler(msg) { + if (msg.cmd && msg.cmd == 'notifyRequest') { + numReqs += 1; + } + } -If accuracy is important, use `cluster.settings`. + // Start workers and listen for messages containing notifyRequest + var numCPUs = require('os').cpus().length; + for (var i = 0; i < numCPUs; i++) { + cluster.fork(); + } -## cluster.setupMaster([settings]) + Object.keys(cluster.workers).forEach(function(id) { + cluster.workers[id].on('message', messageHandler); + }); -* `settings` {Object} - * `exec` {String} file path to worker file. (Default=`process.argv[1]`) - * `args` {Array} string arguments passed to worker. - (Default=`process.argv.slice(2)`) - * `silent` {Boolean} whether or not to send output to parent's stdio. - (Default=`false`) + } else { -`setupMaster` is used to change the default 'fork' behavior. Once called, -the settings will be present in `cluster.settings`. + // Worker processes have a http server. + http.Server(function(req, res) { + res.writeHead(200); + res.end("hello world\n"); -Note that: + // notify master about the request + process.send({ cmd: 'notifyRequest' }); + }).listen(8000); + } -* any settings changes only affect future calls to `.fork()` and have no - effect on workers that are already running -* The *only* attribute of a worker that cannot be set via `.setupMaster()` is - the `env` passed to `.fork()` -* the defaults above apply to the first call only, the defaults for later - calls is the current value at the time of `cluster.setupMaster()` is called +### Event: 'online' -Example: +Similar to the `cluster.on('online')` event, but specific to this worker. - var cluster = require('cluster'); - cluster.setupMaster({ - exec: 'worker.js', - args: ['--use', 'https'], - silent: true - }); - cluster.fork(); // https worker - cluster.setupMaster({ - args: ['--use', 'http'] + cluster.fork().on('online', function() { + // Worker is online }); - cluster.fork(); // http worker - -This can only be called from the master process. -## cluster.fork([env]) +It is not emitted in the worker. -* `env` {Object} Key/value pairs to add to worker process environment. -* return {Worker object} +### worker.disconnect() -Spawn a new worker process. +In a worker, this function will close all servers, wait for the 'close' event on +those servers, and then disconnect the IPC channel. -This can only be called from the master process. +In the master, an internal message is sent to the worker causing it to call +`.disconnect()` on itself. -## cluster.disconnect([callback]) +Causes `.suicide` to be set. -* `callback` {Function} called when all workers are disconnected and handles are - closed +Note that after a server is closed, it will no longer accept new connections, +but connections may be accepted by any other listening worker. Existing +connections will be allowed to close as usual. When no more connections exist, +see [server.close()](net.html#net_event_close), the IPC channel to the worker +will close allowing it to die gracefully. -Calls `.disconnect()` on each worker in `cluster.workers`. +The above applies *only* to server connections, client connections are not +automatically closed by workers, and disconnect does not wait for them to close +before exiting. -When they are disconnected all internal handles will be closed, allowing the -master process to die gracefully if no other event is waiting. +Note that in a worker, `process.disconnect` exists, but it is not this function, +it is [disconnect](child_process.html#child_process_child_disconnect). -The method takes an optional callback argument which will be called when finished. +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 +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. -This can only be called from the master process. + if (cluster.isMaster) { + var worker = cluster.fork(); + var timeout; -## cluster.worker + worker.on('listening', function(address) { + worker.send('shutdown'); + worker.disconnect(); + timeout = setTimeout(function() { + worker.kill(); + }, 2000); + }); -* {Object} + worker.on('disconnect', function() { + clearTimeout(timeout); + }); -A reference to the current worker object. Not available in the master process. + } else if (cluster.isWorker) { + var net = require('net'); + var server = net.createServer(function(socket) { + // connections never end + }); - var cluster = require('cluster'); + server.listen(8000); - if (cluster.isMaster) { - console.log('I am master'); - cluster.fork(); - cluster.fork(); - } else if (cluster.isWorker) { - console.log('I am worker #' + cluster.worker.id); + process.on('message', function(msg) { + if(msg === 'shutdown') { + // initiate graceful close of any connections to server + } + }); } -## cluster.workers +### worker.id -* {Object} +* {Number} -A hash that stores the active worker objects, keyed by `id` field. Makes it -easy to loop through all the workers. It is only available in the master -process. +Each new worker is given its own unique id, this id is stored in the +`id`. -A worker is removed from cluster.workers after the worker has disconnected _and_ -exited. The order between these two events cannot be determined in advance. -However, it is guaranteed that the removal from the cluster.workers list happens -before last `'disconnect'` or `'exit'` event is emitted. +While a worker is alive, this is the key that indexes it in +cluster.workers - // Go through all workers - function eachWorker(callback) { - for (var id in cluster.workers) { - callback(cluster.workers[id]); - } - } - eachWorker(function(worker) { - worker.send('big announcement to all workers'); - }); +### worker.isConnected() -Should you wish to reference a worker over a communication channel, using -the worker's unique id is the easiest way to find the worker. +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 +created. It is disconnected after the `disconnect` event is emitted. - socket.on('data', function(id) { - var worker = cluster.workers[id]; - }); +### worker.isDead() -## Class: Worker +This function returns `true` if the worker's process has terminated (either +because of exiting or being signaled). Otherwise, it returns `false`. -A Worker object contains all public information and method about a worker. -In the master it can be obtained using `cluster.workers`. In a worker -it can be obtained using `cluster.worker`. +### worker.kill([signal='SIGTERM']) -### worker.id +* `signal` {String} Name of the kill signal to send to the worker + process. -* {Number} +This function will kill the worker. In the master, it does this by disconnecting +the `worker.process`, and once disconnected, killing with `signal`. In the +worker, it does it by disconnecting the channel, and then exiting with code `0`. -Each new worker is given its own unique id, this id is stored in the -`id`. +Causes `.suicide` to be set. -While a worker is alive, this is the key that indexes it in -cluster.workers +This method is aliased as `worker.destroy()` for backwards compatibility. + +Note that in a worker, `process.kill()` exists, but it is not this function, +it is [kill](process.html#process_process_kill_pid_signal). ### worker.process @@ -405,24 +330,6 @@ Note that workers will call `process.exit(0)` if the `'disconnect'` event occurs on `process` and `.suicide` is not `true`. This protects against accidental disconnection. -### worker.suicide - -* {Boolean} - -Set by calling `.kill()` or `.disconnect()`, until then it is `undefined`. - -The boolean `worker.suicide` lets you distinguish between voluntary and accidental -exit, the master may choose not to respawn a worker based on this value. - - cluster.on('exit', function(worker, code, signal) { - if (worker.suicide === true) { - console.log('Oh, it was just suicide\' – no need to worry'). - } - }); - - // kill worker - worker.kill(); - ### worker.send(message[, sendHandle][, callback]) * `message` {Object} @@ -450,198 +357,293 @@ This example will echo back all messages from the master: }); } -### worker.kill([signal='SIGTERM']) +### worker.suicide -* `signal` {String} Name of the kill signal to send to the worker - process. +* {Boolean} -This function will kill the worker. In the master, it does this by disconnecting -the `worker.process`, and once disconnected, killing with `signal`. In the -worker, it does it by disconnecting the channel, and then exiting with code `0`. +Set by calling `.kill()` or `.disconnect()`, until then it is `undefined`. + +The boolean `worker.suicide` lets you distinguish between voluntary and accidental +exit, the master may choose not to respawn a worker based on this value. + + cluster.on('exit', function(worker, code, signal) { + if (worker.suicide === true) { + console.log('Oh, it was just suicide\' – no need to worry'). + } + }); + + // kill worker + worker.kill(); + +## Event: 'disconnect' + +* `worker` {Worker object} + +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.disconnect()). + +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 +long-living connections. + + cluster.on('disconnect', function(worker) { + console.log('The worker #' + worker.id + ' has disconnected'); + }); + +## Event: 'exit' + +* `worker` {Worker object} +* `code` {Number} the exit code, if it exited normally. +* `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused + the process to be killed. + +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. + + cluster.on('exit', function(worker, code, signal) { + console.log('worker %d died (%s). restarting...', + worker.process.pid, signal || code); + cluster.fork(); + }); + +See [child_process event: 'exit'](child_process.html#child_process_event_exit). + +## Event: 'fork' + +* `worker` {Worker object} + +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. + + var timeouts = []; + function errorMsg() { + console.error("Something must be wrong with the connection ..."); + } + + cluster.on('fork', function(worker) { + timeouts[worker.id] = setTimeout(errorMsg, 2000); + }); + cluster.on('listening', function(worker, address) { + clearTimeout(timeouts[worker.id]); + }); + cluster.on('exit', function(worker, code, signal) { + clearTimeout(timeouts[worker.id]); + errorMsg(); + }); + +## Event: 'listening' + +* `worker` {Worker object} +* `address` {Object} + +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 event handler is executed with two arguments, the `worker` contains the worker +object and the `address` object contains the following connection properties: +`address`, `port` and `addressType`. This is very useful if the worker is listening +on more than one address. + + cluster.on('listening', function(worker, address) { + console.log("A worker is now connected to " + address.address + ":" + address.port); + }); + +The `addressType` is one of: + +* `4` (TCPv4) +* `6` (TCPv6) +* `-1` (unix domain socket) +* `"udp4"` or `"udp6"` (UDP v4 or v6) + +## Event: 'message' + +* `worker` {Worker object} +* `message` {Object} + +Emitted when any worker receives a message. + +See +[child_process event: 'message'](child_process.html#child_process_event_message). -Causes `.suicide` to be set. +## Event: 'online' -This method is aliased as `worker.destroy()` for backwards compatibility. +* `worker` {Worker object} -Note that in a worker, `process.kill()` exists, but it is not this function, -it is [kill](process.html#process_process_kill_pid_signal). +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. +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. -### worker.disconnect() + cluster.on('online', function(worker) { + console.log("Yay, the worker responded after it was forked"); + }); -In a worker, this function will close all servers, wait for the 'close' event on -those servers, and then disconnect the IPC channel. +## Event: 'setup' -In the master, an internal message is sent to the worker causing it to call -`.disconnect()` on itself. +* `settings` {Object} -Causes `.suicide` to be set. +Emitted every time `.setupMaster()` is called. -Note that after a server is closed, it will no longer accept new connections, -but connections may be accepted by any other listening worker. Existing -connections will be allowed to close as usual. When no more connections exist, -see [server.close()](net.html#net_event_close), the IPC channel to the worker -will close allowing it to die gracefully. +The `settings` object is the `cluster.settings` object at the time +`.setupMaster()` was called and is advisory only, since multiple calls to +`.setupMaster()` can be made in a single tick. -The above applies *only* to server connections, client connections are not -automatically closed by workers, and disconnect does not wait for them to close -before exiting. +If accuracy is important, use `cluster.settings`. -Note that in a worker, `process.disconnect` exists, but it is not this function, -it is [disconnect](child_process.html#child_process_child_disconnect). +## cluster.disconnect([callback]) -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 -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. +* `callback` {Function} called when all workers are disconnected and handles are + closed - if (cluster.isMaster) { - var worker = cluster.fork(); - var timeout; +Calls `.disconnect()` on each worker in `cluster.workers`. - worker.on('listening', function(address) { - worker.send('shutdown'); - worker.disconnect(); - timeout = setTimeout(function() { - worker.kill(); - }, 2000); - }); +When they are disconnected all internal handles will be closed, allowing the +master process to die gracefully if no other event is waiting. - worker.on('disconnect', function() { - clearTimeout(timeout); - }); +The method takes an optional callback argument which will be called when finished. - } else if (cluster.isWorker) { - var net = require('net'); - var server = net.createServer(function(socket) { - // connections never end - }); +This can only be called from the master process. - server.listen(8000); +## cluster.fork([env]) - process.on('message', function(msg) { - if(msg === 'shutdown') { - // initiate graceful close of any connections to server - } - }); - } +* `env` {Object} Key/value pairs to add to worker process environment. +* return {Worker object} -### worker.isDead() +Spawn a new worker process. -This function returns `true` if the worker's process has terminated (either -because of exiting or being signaled). Otherwise, it returns `false`. +This can only be called from the master process. -### worker.isConnected() +## cluster.isMaster -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 -created. It is disconnected after the `disconnect` event is emitted. +* {Boolean} -### Event: 'message' +True if the process is a master. This is determined +by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` is +undefined, then `isMaster` is `true`. -* `message` {Object} +## cluster.isWorker -Similar to the `cluster.on('message')` event, but specific to this worker. +* {Boolean} -This event is the same as the one provided by `child_process.fork()`. +True if the process is not a master (it is the negation of `cluster.isMaster`). -In a worker you can also use `process.on('message')`. +## cluster.schedulingPolicy -As an example, here is a cluster that keeps count of the number of requests -in the master process using the message system: +The scheduling policy, either `cluster.SCHED_RR` for round-robin or +`cluster.SCHED_NONE` to leave it to the operating system. This is a +global setting and effectively frozen once you spawn the first worker +or call `cluster.setupMaster()`, whatever comes first. - var cluster = require('cluster'); - var http = require('http'); +`SCHED_RR` is the default on all operating systems except Windows. +Windows will change to `SCHED_RR` once libuv is able to effectively +distribute IOCP handles without incurring a large performance hit. - if (cluster.isMaster) { +`cluster.schedulingPolicy` can also be set through the +`NODE_CLUSTER_SCHED_POLICY` environment variable. Valid +values are `"rr"` and `"none"`. - // Keep track of http requests - var numReqs = 0; - setInterval(function() { - console.log("numReqs =", numReqs); - }, 1000); +## cluster.settings - // Count requests - function messageHandler(msg) { - if (msg.cmd && msg.cmd == 'notifyRequest') { - numReqs += 1; - } - } +* {Object} + * `execArgv` {Array} list of string arguments passed to the Node.js + executable. (Default=`process.execArgv`) + * `exec` {String} file path to worker file. (Default=`process.argv[1]`) + * `args` {Array} string arguments passed to worker. + (Default=`process.argv.slice(2)`) + * `silent` {Boolean} whether or not to send output to parent's stdio. + (Default=`false`) + * `uid` {Number} Sets the user identity of the process. (See setuid(2).) + * `gid` {Number} Sets the group identity of the process. (See setgid(2).) - // Start workers and listen for messages containing notifyRequest - var numCPUs = require('os').cpus().length; - for (var i = 0; i < numCPUs; i++) { - cluster.fork(); - } +After calling `.setupMaster()` (or `.fork()`) this settings object will contain +the settings, including the default values. - Object.keys(cluster.workers).forEach(function(id) { - cluster.workers[id].on('message', messageHandler); - }); +It is effectively frozen after being set, because `.setupMaster()` can +only be called once. - } else { +This object is not supposed to be changed or set manually, by you. - // Worker processes have a http server. - http.Server(function(req, res) { - res.writeHead(200); - res.end("hello world\n"); +## cluster.setupMaster([settings]) - // notify master about the request - process.send({ cmd: 'notifyRequest' }); - }).listen(8000); - } +* `settings` {Object} + * `exec` {String} file path to worker file. (Default=`process.argv[1]`) + * `args` {Array} string arguments passed to worker. + (Default=`process.argv.slice(2)`) + * `silent` {Boolean} whether or not to send output to parent's stdio. + (Default=`false`) -### Event: 'online' +`setupMaster` is used to change the default 'fork' behavior. Once called, +the settings will be present in `cluster.settings`. -Similar to the `cluster.on('online')` event, but specific to this worker. +Note that: - cluster.fork().on('online', function() { - // Worker is online - }); +* any settings changes only affect future calls to `.fork()` and have no + effect on workers that are already running +* The *only* attribute of a worker that cannot be set via `.setupMaster()` is + the `env` passed to `.fork()` +* the defaults above apply to the first call only, the defaults for later + calls is the current value at the time of `cluster.setupMaster()` is called -It is not emitted in the worker. +Example: -### Event: 'listening' + var cluster = require('cluster'); + cluster.setupMaster({ + exec: 'worker.js', + args: ['--use', 'https'], + silent: true + }); + cluster.fork(); // https worker + cluster.setupMaster({ + args: ['--use', 'http'] + }); + cluster.fork(); // http worker -* `address` {Object} +This can only be called from the master process. -Similar to the `cluster.on('listening')` event, but specific to this worker. +## cluster.worker - cluster.fork().on('listening', function(address) { - // Worker is listening - }); +* {Object} -It is not emitted in the worker. +A reference to the current worker object. Not available in the master process. -### Event: 'disconnect' + var cluster = require('cluster'); -Similar to the `cluster.on('disconnect')` event, but specific to this worker. + if (cluster.isMaster) { + console.log('I am master'); + cluster.fork(); + cluster.fork(); + } else if (cluster.isWorker) { + console.log('I am worker #' + cluster.worker.id); + } - cluster.fork().on('disconnect', function() { - // Worker has disconnected - }); +## cluster.workers -### Event: 'exit' +* {Object} -* `code` {Number} the exit code, if it exited normally. -* `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused - the process to be killed. +A hash that stores the active worker objects, keyed by `id` field. Makes it +easy to loop through all the workers. It is only available in the master +process. -Similar to the `cluster.on('exit')` event, but specific to this worker. +A worker is removed from cluster.workers after the worker has disconnected _and_ +exited. The order between these two events cannot be determined in advance. +However, it is guaranteed that the removal from the cluster.workers list happens +before last `'disconnect'` or `'exit'` event is emitted. - var worker = cluster.fork(); - worker.on('exit', function(code, signal) { - if( signal ) { - console.log("worker was killed by signal: "+signal); - } else if( code !== 0 ) { - console.log("worker exited with error code: "+code); - } else { - console.log("worker success!"); + // Go through all workers + function eachWorker(callback) { + for (var id in cluster.workers) { + callback(cluster.workers[id]); } + } + eachWorker(function(worker) { + worker.send('big announcement to all workers'); }); -### Event: 'error' - -This event is the same as the one provided by `child_process.fork()`. - -In a worker you can also use `process.on('error')`. +Should you wish to reference a worker over a communication channel, using +the worker's unique id is the easiest way to find the worker. -[ChildProcess.send()]: child_process.html#child_process_child_send_message_sendhandle_callback + socket.on('data', function(id) { + var worker = cluster.workers[id]; + }); From cfed942535ae24450a8f1332d49a77ffa4f6f1d1 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 10:51:43 -0500 Subject: [PATCH 05/32] doc: sort console alphabetically Reorders, with no contextual changes, the console documentation alphabetically. --- doc/api/console.markdown | 123 +++++++++++++++++++-------------------- 1 file changed, 61 insertions(+), 62 deletions(-) diff --git a/doc/api/console.markdown b/doc/api/console.markdown index 6e2de6071e64a2..60e08f2b60d0b3 100644 --- a/doc/api/console.markdown +++ b/doc/api/console.markdown @@ -10,6 +10,42 @@ sent to stdout or stderr. For ease of use, `console` is defined as a global object and can be used directly without `require`. +## Class: Console + + + +Use `require('console').Console` or `console.Console` to access this class. + + var Console = require('console').Console; + var Console = console.Console; + +You can use `Console` class to custom simple logger like `console`, but with +different output streams. + +### new Console(stdout[, stderr]) + +Create a new `Console` by passing one or two writable stream instances. +`stdout` is a writable stream to print log or info output. `stderr` +is used for warning or error output. If `stderr` isn't passed, the warning +and error output will be sent to the `stdout`. + + var output = fs.createWriteStream('./stdout.log'); + var errorOutput = fs.createWriteStream('./stderr.log'); + // custom simple logger + var logger = new Console(output, errorOutput); + // use it like console + var count = 5; + logger.log('count: %d', count); + // in stdout.log: count 5 + +The global `console` is a special `Console` whose output is sent to +`process.stdout` and `process.stderr`: + + new Console(process.stdout, process.stderr); + +[assert.ok()]: assert.html#assert_assert_value_message_assert_ok_value_message +[util.format()]: util.html#util_util_format_format + ## console * {Object} @@ -31,30 +67,10 @@ is blocking: In daily use, the blocking/non-blocking dichotomy is not something you should worry about unless you log huge amounts of data. +### console.assert(value[, message][, ...]) -### console.log([data][, ...]) - -Prints to stdout with newline. This function can take multiple arguments in a -`printf()`-like way. Example: - - var count = 5; - console.log('count: %d', count); - // prints 'count: 5' - -If formatting elements are not found in the first string then `util.inspect` -is used on each argument. See [util.format()][] for more information. - -### console.info([data][, ...]) - -Same as `console.log`. - -### console.error([data][, ...]) - -Same as `console.log` but prints to stderr. - -### console.warn([data][, ...]) - -Same as `console.error`. +Similar to [assert.ok()][], but the error message is formatted as +`util.format(message...)`. ### console.dir(obj[, options]) @@ -72,6 +88,26 @@ object. This is useful for inspecting large complicated objects. Defaults to - `colors` - if `true`, then the output will be styled with ANSI color codes. Defaults to `false`. Colors are customizable, see below. +### console.error([data][, ...]) + +Same as `console.log` but prints to stderr. + +### console.info([data][, ...]) + +Same as `console.log`. + +### console.log([data][, ...]) + +Prints to stdout with newline. This function can take multiple arguments in a +`printf()`-like way. Example: + + var count = 5; + console.log('count: %d', count); + // prints 'count: 5' + +If formatting elements are not found in the first string then `util.inspect` +is used on each argument. See [util.format()][] for more information. + ### console.time(timerName) Starts a timer that can be used to compute the duration of an operation. Timers @@ -100,43 +136,6 @@ Example: Print to stderr `'Trace :'`, followed by the formatted message and stack trace to the current position. -### console.assert(value[, message][, ...]) - -Similar to [assert.ok()][], but the error message is formatted as -`util.format(message...)`. - -## Class: Console - - - -Use `require('console').Console` or `console.Console` to access this class. - - var Console = require('console').Console; - var Console = console.Console; - -You can use `Console` class to custom simple logger like `console`, but with -different output streams. - -### new Console(stdout[, stderr]) - -Create a new `Console` by passing one or two writable stream instances. -`stdout` is a writable stream to print log or info output. `stderr` -is used for warning or error output. If `stderr` isn't passed, the warning -and error output will be sent to the `stdout`. - - var output = fs.createWriteStream('./stdout.log'); - var errorOutput = fs.createWriteStream('./stderr.log'); - // custom simple logger - var logger = new Console(output, errorOutput); - // use it like console - var count = 5; - logger.log('count: %d', count); - // in stdout.log: count 5 - -The global `console` is a special `Console` whose output is sent to -`process.stdout` and `process.stderr`: - - new Console(process.stdout, process.stderr); +### console.warn([data][, ...]) -[assert.ok()]: assert.html#assert_assert_value_message_assert_ok_value_message -[util.format()]: util.html#util_util_format_format +Same as `console.error`. From 03dd92c732cd81c411593d9ce349777ae1889f5a Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 10:52:13 -0500 Subject: [PATCH 06/32] doc: sort dns alphabetically Reorders, with no contextual changes, the dns documentation alphabetically. --- doc/api/dns.markdown | 53 ++++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 27 deletions(-) diff --git a/doc/api/dns.markdown b/doc/api/dns.markdown index a945a7d90882d2..f905e8681a3702 100644 --- a/doc/api/dns.markdown +++ b/doc/api/dns.markdown @@ -54,6 +54,11 @@ There are subtle consequences in choosing one or another, please consult the [Implementation considerations section](#dns_implementation_considerations) for more information. +## dns.getServers() + +Returns an array of IP addresses as strings that are currently being used for +resolution + ## dns.lookup(hostname[, options], callback) Resolves a hostname (e.g. `'google.com'`) into the first found A (IPv4) or @@ -152,6 +157,11 @@ The same as [`dns.resolve()`](#dns_dns_resolve_hostname_rrtype_callback), but on The same as [`dns.resolve4()`](#dns_dns_resolve4_hostname_callback) except for IPv6 queries (an `AAAA` query). +## dns.resolveCname(hostname, callback) + +The same as [`dns.resolve()`](#dns_dns_resolve_hostname_rrtype_callback), but only for canonical name records (`CNAME` +records). `addresses` is an array of the canonical name records available for +`hostname` (e.g., `['bar.example.com']`). ## dns.resolveMx(hostname, callback) @@ -160,20 +170,11 @@ The same as [`dns.resolve()`](#dns_dns_resolve_hostname_rrtype_callback), but on `addresses` is an array of MX records, each with a priority and an exchange attribute (e.g. `[{'priority': 10, 'exchange': 'mx.example.com'},...]`). -## dns.resolveTxt(hostname, callback) - -The same as [`dns.resolve()`](#dns_dns_resolve_hostname_rrtype_callback), but only for text queries (`TXT` records). -`addresses` is a 2-d array of the text records available for `hostname` (e.g., -`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of -one record. Depending on the use case, the could be either joined together or -treated separately. - -## dns.resolveSrv(hostname, callback) +## dns.resolveNs(hostname, callback) -The same as [`dns.resolve()`](#dns_dns_resolve_hostname_rrtype_callback), but only for service records (`SRV` records). -`addresses` is an array of the SRV records available for `hostname`. Properties -of SRV records are priority, weight, port, and name (e.g., -`[{'priority': 10, 'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]`). +The same as [`dns.resolve()`](#dns_dns_resolve_hostname_rrtype_callback), but only for name server records (`NS` records). +`addresses` is an array of the name server records available for `hostname` +(e.g., `['ns1.example.com', 'ns2.example.com']`). ## dns.resolveSoa(hostname, callback) @@ -194,17 +195,20 @@ The same as [`dns.resolve()`](#dns_dns_resolve_hostname_rrtype_callback), but on } ``` -## dns.resolveNs(hostname, callback) +## dns.resolveSrv(hostname, callback) -The same as [`dns.resolve()`](#dns_dns_resolve_hostname_rrtype_callback), but only for name server records (`NS` records). -`addresses` is an array of the name server records available for `hostname` -(e.g., `['ns1.example.com', 'ns2.example.com']`). +The same as [`dns.resolve()`](#dns_dns_resolve_hostname_rrtype_callback), but only for service records (`SRV` records). +`addresses` is an array of the SRV records available for `hostname`. Properties +of SRV records are priority, weight, port, and name (e.g., +`[{'priority': 10, 'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]`). -## dns.resolveCname(hostname, callback) +## dns.resolveTxt(hostname, callback) -The same as [`dns.resolve()`](#dns_dns_resolve_hostname_rrtype_callback), but only for canonical name records (`CNAME` -records). `addresses` is an array of the canonical name records available for -`hostname` (e.g., `['bar.example.com']`). +The same as [`dns.resolve()`](#dns_dns_resolve_hostname_rrtype_callback), but only for text queries (`TXT` records). +`addresses` is a 2-d array of the text records available for `hostname` (e.g., +`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of +one record. Depending on the use case, the could be either joined together or +treated separately. ## dns.reverse(ip, callback) @@ -215,11 +219,6 @@ The callback has arguments `(err, hostnames)`. On error, `err` is an `Error` object, where `err.code` is one of the error codes listed below. -## dns.getServers() - -Returns an array of IP addresses as strings that are currently being used for -resolution - ## dns.setServers(servers) Given an array of IP addresses as strings, set them as the servers to use for @@ -314,4 +313,4 @@ 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`_. -[dns.lookup]: #dns_dns_lookup_hostname_options_callback \ No newline at end of file +[dns.lookup]: #dns_dns_lookup_hostname_options_callback From d9e5b6a52d64f1161d7cef6f7da71723bb0195a7 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 11:23:03 -0500 Subject: [PATCH 07/32] doc: sort crypto alphabetically Reorders, with no contextual changes, the crypto documentation alphabetically. --- doc/api/crypto.markdown | 857 ++++++++++++++++++++-------------------- 1 file changed, 434 insertions(+), 423 deletions(-) diff --git a/doc/api/crypto.markdown b/doc/api/crypto.markdown index 6511cfadc9b7c0..9d621a0c9fd3b4 100644 --- a/doc/api/crypto.markdown +++ b/doc/api/crypto.markdown @@ -10,343 +10,328 @@ used as part of a secure HTTPS net or http connection. It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods. +## Class: Certificate -## crypto.setEngine(engine[, flags]) - -Load and set engine for some/all OpenSSL functions (selected by flags). - -`engine` could be either an id or a path to the engine's shared library. - -`flags` is optional and has `ENGINE_METHOD_ALL` value by default. It could take -one of or mix of following flags (defined in `constants` module): - -* `ENGINE_METHOD_RSA` -* `ENGINE_METHOD_DSA` -* `ENGINE_METHOD_DH` -* `ENGINE_METHOD_RAND` -* `ENGINE_METHOD_ECDH` -* `ENGINE_METHOD_ECDSA` -* `ENGINE_METHOD_CIPHERS` -* `ENGINE_METHOD_DIGESTS` -* `ENGINE_METHOD_STORE` -* `ENGINE_METHOD_PKEY_METH` -* `ENGINE_METHOD_PKEY_ASN1_METH` -* `ENGINE_METHOD_ALL` -* `ENGINE_METHOD_NONE` +The class used for working with signed public key & challenges. The most +common usage for this series of functions is when dealing with the `` +element. http://www.openssl.org/docs/apps/spkac.html +Returned by `crypto.Certificate`. -## crypto.getCiphers() +### Certificate.exportChallenge(spkac) -Returns an array with the names of the supported ciphers. +Exports the encoded challenge associated with the SPKAC. -Example: +### Certificate.exportPublicKey(spkac) - var ciphers = crypto.getCiphers(); - console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...] +Exports the encoded public key from the supplied SPKAC. +### Certificate.verifySpkac(spkac) -## crypto.getHashes() +Returns true of false based on the validity of the SPKAC. -Returns an array with the names of the supported hash algorithms. +## Class: Cipher -Example: +Class for encrypting data. - var hashes = crypto.getHashes(); - console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...] +Returned by `crypto.createCipher` and `crypto.createCipheriv`. +Cipher objects are [streams](stream.html) that are both readable and +writable. The written plain text data is used to produce the +encrypted data on the readable side. The legacy `update` and `final` +methods are also supported. -## crypto.getCurves() +### cipher.final([output_encoding]) -Returns an array with the names of the supported elliptic curves. +Returns any remaining enciphered contents, with `output_encoding` +being one of: `'binary'`, `'base64'` or `'hex'`. If no encoding is +provided, then a buffer is returned. -Example: +Note: `cipher` object can not be used after `final()` method has been +called. - var curves = crypto.getCurves(); - console.log(curves); // ['secp256k1', 'secp384r1', ...] +### cipher.getAuthTag() +For authenticated encryption modes (currently supported: GCM), this +method returns a `Buffer` that represents the _authentication tag_ that +has been computed from the given data. Should be called after +encryption has been completed using the `final` method! -## crypto.createCredentials(details) +### cipher.setAAD(buffer) - Stability: 0 - Deprecated: Use [tls.createSecureContext][] instead. +For authenticated encryption modes (currently supported: GCM), this +method sets the value used for the additional authenticated data (AAD) input +parameter. -Creates a credentials object, with the optional details being a -dictionary with keys: +### cipher.setAutoPadding(auto_padding=true) -* `pfx` : A string or buffer holding the PFX or PKCS12 encoded private - key, certificate and CA certificates -* `key` : A string holding the PEM encoded private key -* `passphrase` : A string of passphrase for the private key or pfx -* `cert` : A string holding the PEM encoded certificate -* `ca` : Either a string or list of strings of PEM encoded CA - certificates to trust. -* `crl` : Either a string or list of strings of PEM encoded CRLs - (Certificate Revocation List) -* `ciphers`: A string describing the ciphers to use or exclude. - Consult - - for details on the format. +You can disable automatic padding of the input data to block size. If +`auto_padding` is false, the length of the entire input data must be a +multiple of the cipher's block size or `final` will fail. Useful for +non-standard padding, e.g. using `0x0` instead of PKCS padding. You +must call this before `cipher.final`. -If no 'ca' details are given, then Node.js will use the default -publicly trusted list of CAs as given in -. +### cipher.update(data[, input_encoding][, output_encoding]) +Updates the cipher with `data`, the encoding of which is given in +`input_encoding` and can be `'utf8'`, `'ascii'` or `'binary'`. If no +encoding is provided, then a buffer is expected. +If `data` is a `Buffer` then `input_encoding` is ignored. -## crypto.createHash(algorithm) +The `output_encoding` specifies the output format of the enciphered +data, and can be `'binary'`, `'base64'` or `'hex'`. If no encoding is +provided, then a buffer is returned. -Creates and returns a hash object, a cryptographic hash with the given -algorithm which can be used to generate hash digests. +Returns the enciphered contents, and can be called many times with new +data as it is streamed. -`algorithm` is dependent on the available algorithms supported by the -version of OpenSSL on the platform. Examples are `'sha1'`, `'md5'`, -`'sha256'`, `'sha512'`, etc. On recent releases, `openssl -list-message-digest-algorithms` will display the available digest -algorithms. +## Class: Decipher -Example: this program that takes the sha1 sum of a file +Class for decrypting data. - var filename = process.argv[2]; - var crypto = require('crypto'); - var fs = require('fs'); +Returned by `crypto.createDecipher` and `crypto.createDecipheriv`. - var shasum = crypto.createHash('sha1'); +Decipher objects are [streams](stream.html) that are both readable and +writable. The written enciphered data is used to produce the +plain-text data on the the readable side. The legacy `update` and +`final` methods are also supported. - var s = fs.ReadStream(filename); - s.on('data', function(d) { - shasum.update(d); - }); +### decipher.final([output_encoding]) - s.on('end', function() { - var d = shasum.digest('hex'); - console.log(d + ' ' + filename); - }); +Returns any remaining plaintext which is deciphered, with +`output_encoding` being one of: `'binary'`, `'ascii'` or `'utf8'`. If +no encoding is provided, then a buffer is returned. -## Class: Hash +Note: `decipher` object can not be used after `final()` method has been +called. -The class for creating hash digests of data. +### decipher.setAAD(buffer) -It is a [stream](stream.html) that is both readable and writable. The -written data is used to compute the hash. Once the writable side of -the stream is ended, use the `read()` method to get the computed hash -digest. The legacy `update` and `digest` methods are also supported. +For authenticated encryption modes (currently supported: GCM), this +method sets the value used for the additional authenticated data (AAD) input +parameter. -Returned by `crypto.createHash`. +### decipher.setAuthTag(buffer) -### hash.update(data[, input_encoding]) +For authenticated encryption modes (currently supported: GCM), this +method must be used to pass in the received _authentication tag_. +If no tag is provided or if the ciphertext has been tampered with, +`final` will throw, thus indicating that the ciphertext should +be discarded due to failed authentication. -Updates the hash content with the given `data`, the encoding of which -is given in `input_encoding` and can be `'utf8'`, `'ascii'` or -`'binary'`. If no encoding is provided, and the input is a string, an -encoding of `'binary'` is enforced. If `data` is a `Buffer` then -`input_encoding` is ignored. +### decipher.setAutoPadding(auto_padding=true) -This can be called many times with new data as it is streamed. +You can disable auto padding if the data has been encrypted without +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 +the ciphers block size. You must call this before streaming data to +`decipher.update`. -### hash.digest([encoding]) +### decipher.update(data[, input_encoding][, output_encoding]) -Calculates the digest of all of the passed data to be hashed. The -`encoding` can be `'hex'`, `'binary'` or `'base64'`. If no encoding -is provided, then a buffer is returned. +Updates the decipher with `data`, which is encoded in `'binary'`, +`'base64'` or `'hex'`. If no encoding is provided, then a buffer is +expected. +If `data` is a `Buffer` then `input_encoding` is ignored. -Note: `hash` object can not be used after `digest()` method has been -called. +The `output_decoding` specifies in what format to return the +deciphered plaintext: `'binary'`, `'ascii'` or `'utf8'`. If no +encoding is provided, then a buffer is returned. +## Class: DiffieHellman -## crypto.createHmac(algorithm, key) +The class for creating Diffie-Hellman key exchanges. -Creates and returns a hmac object, a cryptographic hmac with the given -algorithm and key. +Returned by `crypto.createDiffieHellman`. -It is a [stream](stream.html) that is both readable and writable. The -written data is used to compute the hmac. Once the writable side of -the stream is ended, use the `read()` method to get the computed -digest. The legacy `update` and `digest` methods are also supported. +### diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding]) -`algorithm` is dependent on the available algorithms supported by -OpenSSL - see createHash above. `key` is the hmac key to be used. +Computes the shared secret using `other_public_key` as the other +party's public key and returns the computed shared secret. Supplied +key is interpreted using specified `input_encoding`, and secret is +encoded using specified `output_encoding`. Encodings can be +`'binary'`, `'hex'`, or `'base64'`. If the input encoding is not +provided, then a buffer is expected. -## Class: Hmac +If no output encoding is given, then a buffer is returned. -Class for creating cryptographic hmac content. +### diffieHellman.generateKeys([encoding]) -Returned by `crypto.createHmac`. +Generates private and public Diffie-Hellman key values, and returns +the public key in the specified encoding. This key should be +transferred to the other party. Encoding can be `'binary'`, `'hex'`, +or `'base64'`. If no encoding is provided, then a buffer is returned. -### hmac.update(data) +### diffieHellman.getGenerator([encoding]) -Update the hmac content with the given `data`. This can be called -many times with new data as it is streamed. +Returns the Diffie-Hellman generator in the specified encoding, which can +be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, +then a buffer is returned. -### hmac.digest([encoding]) +### diffieHellman.getPrime([encoding]) -Calculates the digest of all of the passed data to the hmac. The -`encoding` can be `'hex'`, `'binary'` or `'base64'`. If no encoding -is provided, then a buffer is returned. +Returns the Diffie-Hellman prime in the specified encoding, which can +be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, +then a buffer is returned. -Note: `hmac` object can not be used after `digest()` method has been -called. +### diffieHellman.getPrivateKey([encoding]) +Returns the Diffie-Hellman private key in the specified encoding, +which can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is +provided, then a buffer is returned. -## crypto.createCipher(algorithm, password) +### diffieHellman.getPublicKey([encoding]) -Creates and returns a cipher object, with the given algorithm and -password. +Returns the Diffie-Hellman public key in the specified encoding, which +can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, +then a buffer is returned. -`algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On -recent releases, `openssl list-cipher-algorithms` will display the -available cipher algorithms. `password` is used to derive key and IV, -which must be a `'binary'` encoded string or a [buffer](buffer.html). +### diffieHellman.setPrivateKey(private_key[, encoding]) -It is a [stream](stream.html) that is both readable and writable. The -written data 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` and `final` methods are also supported. +Sets the Diffie-Hellman private key. Key encoding can be `'binary'`, +`'hex'` or `'base64'`. If no encoding is provided, then a buffer is +expected. -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 -salt allows dictionary attacks as the same password always creates the same key. -The low iteration count and non-cryptographically secure hash algorithm allow -passwords to be tested very rapidly. +### diffieHellman.setPublicKey(public_key[, encoding]) -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 -then use [createCipheriv()][] to create the cipher stream. +Sets the Diffie-Hellman public key. Key encoding can be `'binary'`, +`'hex'` or `'base64'`. If no encoding is provided, then a buffer is +expected. -## crypto.createCipheriv(algorithm, key, iv) +### diffieHellman.verifyError -Creates and returns a cipher object, with the given algorithm, key and -iv. +A bit field containing any warnings and/or errors as a result of a check performed +during initialization. The following values are valid for this property +(defined in `constants` module): -`algorithm` is the same as the argument to `createCipher()`. `key` is -the raw key used by the algorithm. `iv` is an [initialization -vector](http://en.wikipedia.org/wiki/Initialization_vector). +* `DH_CHECK_P_NOT_SAFE_PRIME` +* `DH_CHECK_P_NOT_PRIME` +* `DH_UNABLE_TO_CHECK_GENERATOR` +* `DH_NOT_SUITABLE_GENERATOR` -`key` and `iv` must be `'binary'` encoded strings or -[buffers](buffer.html). +## Class: ECDH -## Class: Cipher +The class for creating EC Diffie-Hellman key exchanges. -Class for encrypting data. +Returned by `crypto.createECDH`. -Returned by `crypto.createCipher` and `crypto.createCipheriv`. +### ECDH.computeSecret(other_public_key[, input_encoding][, output_encoding]) -Cipher objects are [streams](stream.html) that are both readable and -writable. The written plain text data is used to produce the -encrypted data on the readable side. The legacy `update` and `final` -methods are also supported. +Computes the shared secret using `other_public_key` as the other +party's public key and returns the computed shared secret. Supplied +key is interpreted using specified `input_encoding`, and secret is +encoded using specified `output_encoding`. Encodings can be +`'binary'`, `'hex'`, or `'base64'`. If the input encoding is not +provided, then a buffer is expected. -### cipher.update(data[, input_encoding][, output_encoding]) +If no output encoding is given, then a buffer is returned. -Updates the cipher with `data`, the encoding of which is given in -`input_encoding` and can be `'utf8'`, `'ascii'` or `'binary'`. If no -encoding is provided, then a buffer is expected. -If `data` is a `Buffer` then `input_encoding` is ignored. +### ECDH.generateKeys([encoding[, format]]) -The `output_encoding` specifies the output format of the enciphered -data, and can be `'binary'`, `'base64'` or `'hex'`. If no encoding is -provided, then a buffer is returned. +Generates private and public EC Diffie-Hellman key values, and returns +the public key in the specified format and encoding. This key should be +transferred to the other party. -Returns the enciphered contents, and can be called many times with new -data as it is streamed. +Format specifies point encoding and can be `'compressed'`, `'uncompressed'`, or +`'hybrid'`. If no format is provided - the point will be returned in +`'uncompressed'` format. -### cipher.final([output_encoding]) +Encoding can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, +then a buffer is returned. -Returns any remaining enciphered contents, with `output_encoding` -being one of: `'binary'`, `'base64'` or `'hex'`. If no encoding is +### ECDH.getPrivateKey([encoding]) + +Returns the EC Diffie-Hellman private key in the specified encoding, +which can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, then a buffer is returned. -Note: `cipher` object can not be used after `final()` method has been -called. -### cipher.setAutoPadding(auto_padding=true) +### ECDH.getPublicKey([encoding[, format]]) -You can disable automatic padding of the input data to block size. If -`auto_padding` is false, the length of the entire input data must be a -multiple of the cipher's block size or `final` will fail. Useful for -non-standard padding, e.g. using `0x0` instead of PKCS padding. You -must call this before `cipher.final`. +Returns the EC Diffie-Hellman public key in the specified encoding and format. -### cipher.getAuthTag() +Format specifies point encoding and can be `'compressed'`, `'uncompressed'`, or +`'hybrid'`. If no format is provided - the point will be returned in +`'uncompressed'` format. -For authenticated encryption modes (currently supported: GCM), this -method returns a `Buffer` that represents the _authentication tag_ that -has been computed from the given data. Should be called after -encryption has been completed using the `final` method! +Encoding can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, +then a buffer is returned. +### ECDH.setPrivateKey(private_key[, encoding]) -### cipher.setAAD(buffer) +Sets the EC Diffie-Hellman private key. Key encoding can be `'binary'`, +`'hex'` or `'base64'`. If no encoding is provided, then a buffer is +expected. -For authenticated encryption modes (currently supported: GCM), this -method sets the value used for the additional authenticated data (AAD) input -parameter. +Example (obtaining a shared secret): + var crypto = require('crypto'); + var alice = crypto.createECDH('secp256k1'); + var bob = crypto.createECDH('secp256k1'); -## crypto.createDecipher(algorithm, password) + alice.generateKeys(); + bob.generateKeys(); -Creates and returns a decipher object, with the given algorithm and -key. This is the mirror of the [createCipher()][] above. + var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); -## crypto.createDecipheriv(algorithm, key, iv) + /* alice_secret and bob_secret should be the same */ + console.log(alice_secret == bob_secret); -Creates and returns a decipher object, with the given algorithm, key -and iv. This is the mirror of the [createCipheriv()][] above. +### ECDH.setPublicKey(public_key[, encoding]) -## Class: Decipher +Sets the EC Diffie-Hellman public key. Key encoding can be `'binary'`, +`'hex'` or `'base64'`. If no encoding is provided, then a buffer is +expected. -Class for decrypting data. +## Class: Hash -Returned by `crypto.createDecipher` and `crypto.createDecipheriv`. +The class for creating hash digests of data. -Decipher objects are [streams](stream.html) that are both readable and -writable. The written enciphered data is used to produce the -plain-text data on the the readable side. The legacy `update` and -`final` methods are also supported. +It is a [stream](stream.html) that is both readable and writable. The +written data is used to compute the hash. Once the writable side of +the stream is ended, use the `read()` method to get the computed hash +digest. The legacy `update` and `digest` methods are also supported. -### decipher.update(data[, input_encoding][, output_encoding]) +Returned by `crypto.createHash`. -Updates the decipher with `data`, which is encoded in `'binary'`, -`'base64'` or `'hex'`. If no encoding is provided, then a buffer is -expected. -If `data` is a `Buffer` then `input_encoding` is ignored. +### hash.digest([encoding]) -The `output_decoding` specifies in what format to return the -deciphered plaintext: `'binary'`, `'ascii'` or `'utf8'`. If no -encoding is provided, then a buffer is returned. +Calculates the digest of all of the passed data to be hashed. The +`encoding` can be `'hex'`, `'binary'` or `'base64'`. If no encoding +is provided, then a buffer is returned. -### decipher.final([output_encoding]) +Note: `hash` object can not be used after `digest()` method has been +called. -Returns any remaining plaintext which is deciphered, with -`output_encoding` being one of: `'binary'`, `'ascii'` or `'utf8'`. If -no encoding is provided, then a buffer is returned. +### hash.update(data[, input_encoding]) -Note: `decipher` object can not be used after `final()` method has been -called. +Updates the hash content with the given `data`, the encoding of which +is given in `input_encoding` and can be `'utf8'`, `'ascii'` or +`'binary'`. If no encoding is provided, and the input is a string, an +encoding of `'binary'` is enforced. If `data` is a `Buffer` then +`input_encoding` is ignored. -### decipher.setAutoPadding(auto_padding=true) +This can be called many times with new data as it is streamed. -You can disable auto padding if the data has been encrypted without -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 -the ciphers block size. You must call this before streaming data to -`decipher.update`. +## Class: Hmac -### decipher.setAuthTag(buffer) +Class for creating cryptographic hmac content. -For authenticated encryption modes (currently supported: GCM), this -method must be used to pass in the received _authentication tag_. -If no tag is provided or if the ciphertext has been tampered with, -`final` will throw, thus indicating that the ciphertext should -be discarded due to failed authentication. +Returned by `crypto.createHmac`. -### decipher.setAAD(buffer) +### hmac.digest([encoding]) -For authenticated encryption modes (currently supported: GCM), this -method sets the value used for the additional authenticated data (AAD) input -parameter. +Calculates the digest of all of the passed data to the hmac. The +`encoding` can be `'hex'`, `'binary'` or `'base64'`. If no encoding +is provided, then a buffer is returned. +Note: `hmac` object can not be used after `digest()` method has been +called. -## crypto.createSign(algorithm) +### hmac.update(data) -Creates and returns a signing object, with the given algorithm. On -recent OpenSSL releases, `openssl list-public-key-algorithms` will -display the available signing algorithms. Examples are `'RSA-SHA256'`. +Update the hmac content with the given `data`. This can be called +many times with new data as it is streamed. ## Class: Sign @@ -384,11 +369,6 @@ returned. Note: `sign` object can not be used after `sign()` method has been called. -## crypto.createVerify(algorithm) - -Creates and returns a verification object, with the given algorithm. -This is the mirror of the signing object above. - ## Class: Verify Class for verifying signatures. @@ -421,120 +401,104 @@ the data and public key. Note: `verifier` object can not be used after `verify()` method has been called. -## crypto.createDiffieHellman(prime_length[, generator]) - -Creates a Diffie-Hellman key exchange object and generates a prime of -`prime_length` bits and using an optional specific numeric `generator`. -If no `generator` is specified, then `2` is used. - -## crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding]) - -Creates a Diffie-Hellman key exchange object using the supplied `prime` and an -optional specific `generator`. -`generator` can be a number, string, or Buffer. -If no `generator` is specified, then `2` is used. -`prime_encoding` and `generator_encoding` can be `'binary'`, `'hex'`, or `'base64'`. -If no `prime_encoding` is specified, then a Buffer is expected for `prime`. -If no `generator_encoding` is specified, then a Buffer is expected for `generator`. - -## Class: DiffieHellman - -The class for creating Diffie-Hellman key exchanges. - -Returned by `crypto.createDiffieHellman`. - -### diffieHellman.verifyError - -A bit field containing any warnings and/or errors as a result of a check performed -during initialization. The following values are valid for this property -(defined in `constants` module): +## crypto.DEFAULT_ENCODING -* `DH_CHECK_P_NOT_SAFE_PRIME` -* `DH_CHECK_P_NOT_PRIME` -* `DH_UNABLE_TO_CHECK_GENERATOR` -* `DH_NOT_SUITABLE_GENERATOR` +The default encoding to use for functions that can take either strings +or buffers. The default value is `'buffer'`, which makes it default +to using Buffer objects. This is here to make the crypto module more +easily compatible with legacy programs that expected `'binary'` to be +the default encoding. -### diffieHellman.generateKeys([encoding]) +Note that new programs will probably expect buffers, so only use this +as a temporary measure. -Generates private and public Diffie-Hellman key values, and returns -the public key in the specified encoding. This key should be -transferred to the other party. Encoding can be `'binary'`, `'hex'`, -or `'base64'`. If no encoding is provided, then a buffer is returned. +## crypto.createCipher(algorithm, password) -### diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding]) +Creates and returns a cipher object, with the given algorithm and +password. -Computes the shared secret using `other_public_key` as the other -party's public key and returns the computed shared secret. Supplied -key is interpreted using specified `input_encoding`, and secret is -encoded using specified `output_encoding`. Encodings can be -`'binary'`, `'hex'`, or `'base64'`. If the input encoding is not -provided, then a buffer is expected. +`algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On +recent releases, `openssl list-cipher-algorithms` will display the +available cipher algorithms. `password` is used to derive key and IV, +which must be a `'binary'` encoded string or a [buffer](buffer.html). -If no output encoding is given, then a buffer is returned. +It is a [stream](stream.html) that is both readable and writable. The +written data 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` and `final` methods are also supported. -### diffieHellman.getPrime([encoding]) +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 +salt allows dictionary attacks as the same password always creates the same key. +The low iteration count and non-cryptographically secure hash algorithm allow +passwords to be tested very rapidly. -Returns the Diffie-Hellman prime in the specified encoding, which can -be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, -then a buffer is returned. +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 +then use [createCipheriv()][] to create the cipher stream. -### diffieHellman.getGenerator([encoding]) +## crypto.createCipheriv(algorithm, key, iv) -Returns the Diffie-Hellman generator in the specified encoding, which can -be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, -then a buffer is returned. +Creates and returns a cipher object, with the given algorithm, key and +iv. -### diffieHellman.getPublicKey([encoding]) +`algorithm` is the same as the argument to `createCipher()`. `key` is +the raw key used by the algorithm. `iv` is an [initialization +vector](http://en.wikipedia.org/wiki/Initialization_vector). -Returns the Diffie-Hellman public key in the specified encoding, which -can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, -then a buffer is returned. +`key` and `iv` must be `'binary'` encoded strings or +[buffers](buffer.html). -### diffieHellman.getPrivateKey([encoding]) +## crypto.createCredentials(details) -Returns the Diffie-Hellman private key in the specified encoding, -which can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is -provided, then a buffer is returned. + Stability: 0 - Deprecated: Use [tls.createSecureContext][] instead. -### diffieHellman.setPublicKey(public_key[, encoding]) +Creates a credentials object, with the optional details being a +dictionary with keys: -Sets the Diffie-Hellman public key. Key encoding can be `'binary'`, -`'hex'` or `'base64'`. If no encoding is provided, then a buffer is -expected. +* `pfx` : A string or buffer holding the PFX or PKCS12 encoded private + key, certificate and CA certificates +* `key` : A string holding the PEM encoded private key +* `passphrase` : A string of passphrase for the private key or pfx +* `cert` : A string holding the PEM encoded certificate +* `ca` : Either a string or list of strings of PEM encoded CA + certificates to trust. +* `crl` : Either a string or list of strings of PEM encoded CRLs + (Certificate Revocation List) +* `ciphers`: A string describing the ciphers to use or exclude. + Consult + + for details on the format. -### diffieHellman.setPrivateKey(private_key[, encoding]) +If no 'ca' details are given, then Node.js will use the default +publicly trusted list of CAs as given in +. -Sets the Diffie-Hellman private key. Key encoding can be `'binary'`, -`'hex'` or `'base64'`. If no encoding is provided, then a buffer is -expected. +## crypto.createDecipher(algorithm, password) -## crypto.getDiffieHellman(group_name) +Creates and returns a decipher object, with the given algorithm and +key. This is the mirror of the [createCipher()][] above. -Creates a predefined Diffie-Hellman key exchange object. The -supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC -2412][]) and `'modp14'`, `'modp15'`, `'modp16'`, `'modp17'`, -`'modp18'` (defined in [RFC 3526][]). The returned object mimics the -interface of objects created by [crypto.createDiffieHellman()][] -above, but will not allow to change the keys (with -[diffieHellman.setPublicKey()][] for example). The advantage of using -this routine is that the parties don't have to generate nor exchange -group modulus beforehand, saving both processor and communication -time. +## crypto.createDecipheriv(algorithm, key, iv) -Example (obtaining a shared secret): +Creates and returns a decipher object, with the given algorithm, key +and iv. This is the mirror of the [createCipheriv()][] above. - var crypto = require('crypto'); - var alice = crypto.getDiffieHellman('modp5'); - var bob = crypto.getDiffieHellman('modp5'); +## crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding]) - alice.generateKeys(); - bob.generateKeys(); +Creates a Diffie-Hellman key exchange object using the supplied `prime` and an +optional specific `generator`. +`generator` can be a number, string, or Buffer. +If no `generator` is specified, then `2` is used. +`prime_encoding` and `generator_encoding` can be `'binary'`, `'hex'`, or `'base64'`. +If no `prime_encoding` is specified, then a Buffer is expected for `prime`. +If no `generator_encoding` is specified, then a Buffer is expected for `generator`. - var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); - var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); +## crypto.createDiffieHellman(prime_length[, generator]) - /* alice_secret and bob_secret should be the same */ - console.log(alice_secret == bob_secret); +Creates a Diffie-Hellman key exchange object and generates a prime of +`prime_length` bits and using an optional specific numeric `generator`. +If no `generator` is specified, then `2` is used. ## crypto.createECDH(curve_name) @@ -544,70 +508,95 @@ obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve. -## Class: ECDH +## crypto.createHash(algorithm) -The class for creating EC Diffie-Hellman key exchanges. +Creates and returns a hash object, a cryptographic hash with the given +algorithm which can be used to generate hash digests. -Returned by `crypto.createECDH`. +`algorithm` is dependent on the available algorithms supported by the +version of OpenSSL on the platform. Examples are `'sha256'`, +`'sha512'`, etc. On recent releases, `openssl +list-message-digest-algorithms` will display the available digest +algorithms. -### ECDH.generateKeys([encoding[, format]]) +Example: this program that takes the sha256 sum of a file -Generates private and public EC Diffie-Hellman key values, and returns -the public key in the specified format and encoding. This key should be -transferred to the other party. + var filename = process.argv[2]; + var crypto = require('crypto'); + var fs = require('fs'); -Format specifies point encoding and can be `'compressed'`, `'uncompressed'`, or -`'hybrid'`. If no format is provided - the point will be returned in -`'uncompressed'` format. + var shasum = crypto.createHash('sha256'); -Encoding can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, -then a buffer is returned. + var s = fs.ReadStream(filename); + s.on('data', function(d) { + shasum.update(d); + }); -### ECDH.computeSecret(other_public_key[, input_encoding][, output_encoding]) + s.on('end', function() { + var d = shasum.digest('hex'); + console.log(d + ' ' + filename); + }); -Computes the shared secret using `other_public_key` as the other -party's public key and returns the computed shared secret. Supplied -key is interpreted using specified `input_encoding`, and secret is -encoded using specified `output_encoding`. Encodings can be -`'binary'`, `'hex'`, or `'base64'`. If the input encoding is not -provided, then a buffer is expected. +## crypto.createHmac(algorithm, key) -If no output encoding is given, then a buffer is returned. +Creates and returns a hmac object, a cryptographic hmac with the given +algorithm and key. -### ECDH.getPublicKey([encoding[, format]]) +It is a [stream](stream.html) that is both readable and writable. The +written data is used to compute the hmac. Once the writable side of +the stream is ended, use the `read()` method to get the computed +digest. The legacy `update` and `digest` methods are also supported. -Returns the EC Diffie-Hellman public key in the specified encoding and format. +`algorithm` is dependent on the available algorithms supported by +OpenSSL - see createHash above. `key` is the hmac key to be used. -Format specifies point encoding and can be `'compressed'`, `'uncompressed'`, or -`'hybrid'`. If no format is provided - the point will be returned in -`'uncompressed'` format. +## crypto.createSign(algorithm) -Encoding can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, -then a buffer is returned. +Creates and returns a signing object, with the given algorithm. On +recent OpenSSL releases, `openssl list-public-key-algorithms` will +display the available signing algorithms. Examples are `'RSA-SHA256'`. -### ECDH.getPrivateKey([encoding]) +## crypto.createVerify(algorithm) -Returns the EC Diffie-Hellman private key in the specified encoding, -which can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is -provided, then a buffer is returned. +Creates and returns a verification object, with the given algorithm. +This is the mirror of the signing object above. -### ECDH.setPublicKey(public_key[, encoding]) +## crypto.getCiphers() -Sets the EC Diffie-Hellman public key. Key encoding can be `'binary'`, -`'hex'` or `'base64'`. If no encoding is provided, then a buffer is -expected. +Returns an array with the names of the supported ciphers. -### ECDH.setPrivateKey(private_key[, encoding]) +Example: -Sets the EC Diffie-Hellman private key. Key encoding can be `'binary'`, -`'hex'` or `'base64'`. If no encoding is provided, then a buffer is -expected. + var ciphers = crypto.getCiphers(); + console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...] + +## crypto.getCurves() + +Returns an array with the names of the supported elliptic curves. + +Example: + + var curves = crypto.getCurves(); + console.log(curves); // ['secp256k1', 'secp384r1', ...] + +## crypto.getDiffieHellman(group_name) + +Creates a predefined Diffie-Hellman key exchange object. The +supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in +[RFC 2412][], but see [Caveats](#crypto_caveats)) and `'modp14'`, +`'modp15'`, `'modp16'`, `'modp17'`, `'modp18'` (defined in +[RFC 3526][]). The returned object mimics the interface of objects +created by [crypto.createDiffieHellman()][] above, but will not allow +changing the keys (with [diffieHellman.setPublicKey()][] for example). +The advantage of using this routine is that the parties do not have to +generate nor exchange group modulus beforehand, saving both processor +and communication time. Example (obtaining a shared secret): var crypto = require('crypto'); - var alice = crypto.createECDH('secp256k1'); - var bob = crypto.createECDH('secp256k1'); + var alice = crypto.getDiffieHellman('modp14'); + var bob = crypto.getDiffieHellman('modp14'); alice.generateKeys(); bob.generateKeys(); @@ -618,6 +607,15 @@ Example (obtaining a shared secret): /* alice_secret and bob_secret should be the same */ console.log(alice_secret == bob_secret); +## crypto.getHashes() + +Returns an array with the names of the supported hash algorithms. + +Example: + + var hashes = crypto.getHashes(); + console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...] + ## crypto.pbkdf2(password, salt, iterations, keylen[, digest], callback) Asynchronous PBKDF2 function. Applies the selected HMAC digest function @@ -640,44 +638,33 @@ You can get a list of supported digest functions with Synchronous PBKDF2 function. Returns derivedKey or throws error. -## crypto.randomBytes(size[, callback]) - -Generates cryptographically strong pseudo-random data. Usage: - - // async - crypto.randomBytes(256, function(ex, buf) { - if (ex) throw ex; - console.log('Have %d bytes of random data: %s', buf.length, buf); - }); - - // sync - const buf = crypto.randomBytes(256); - console.log('Have %d bytes of random data: %s', buf.length, buf); - -NOTE: This will block if there is insufficient entropy, although it should -normally never take longer than a few milliseconds. The only time when this -may conceivably block is right after boot, when the whole system is still -low on entropy. +## crypto.privateDecrypt(private_key, buffer) -## Class: Certificate +Decrypts `buffer` with `private_key`. -The class used for working with signed public key & challenges. The most -common usage for this series of functions is when dealing with the `` -element. http://www.openssl.org/docs/apps/spkac.html +`private_key` can be an object or a string. If `private_key` is a string, it is +treated as the key with no passphrase and will use `RSA_PKCS1_OAEP_PADDING`. -Returned by `crypto.Certificate`. +`private_key`: -### Certificate.verifySpkac(spkac) +* `key` : A string holding the PEM encoded private key +* `passphrase` : An optional string of passphrase for the private key +* `padding` : An optional padding value, one of the following: + * `constants.RSA_NO_PADDING` + * `constants.RSA_PKCS1_PADDING` + * `constants.RSA_PKCS1_OAEP_PADDING` -Returns true of false based on the validity of the SPKAC. +NOTE: All paddings are defined in `constants` module. -### Certificate.exportChallenge(spkac) +## crypto.privateEncrypt(private_key, buffer) -Exports the encoded challenge associated with the SPKAC. +See above for details. Has the same API as `crypto.privateDecrypt`. +Default padding is `RSA_PKCS1_PADDING`. -### Certificate.exportPublicKey(spkac) +## crypto.publicDecrypt(public_key, buffer) -Exports the encoded public key from the supplied SPKAC. +See above for details. Has the same API as `crypto.publicEncrypt`. Default +padding is `RSA_PKCS1_PADDING`. ## crypto.publicEncrypt(public_key, buffer) @@ -699,44 +686,47 @@ key to this method. NOTE: All paddings are defined in `constants` module. -## crypto.publicDecrypt(public_key, buffer) - -See above for details. Has the same API as `crypto.publicEncrypt`. Default -padding is `RSA_PKCS1_PADDING`. - -## crypto.privateDecrypt(private_key, buffer) - -Decrypts `buffer` with `private_key`. +## crypto.randomBytes(size[, callback]) -`private_key` can be an object or a string. If `private_key` is a string, it is -treated as the key with no passphrase and will use `RSA_PKCS1_OAEP_PADDING`. +Generates cryptographically strong pseudo-random data. Usage: -`private_key`: + // async + crypto.randomBytes(256, function(ex, buf) { + if (ex) throw ex; + console.log('Have %d bytes of random data: %s', buf.length, buf); + }); -* `key` : A string holding the PEM encoded private key -* `passphrase` : An optional string of passphrase for the private key -* `padding` : An optional padding value, one of the following: - * `constants.RSA_NO_PADDING` - * `constants.RSA_PKCS1_PADDING` - * `constants.RSA_PKCS1_OAEP_PADDING` + // sync + const buf = crypto.randomBytes(256); + console.log('Have %d bytes of random data: %s', buf.length, buf); -NOTE: All paddings are defined in `constants` module. +NOTE: This will block if there is insufficient entropy, although it should +normally never take longer than a few milliseconds. The only time when this +may conceivably block is right after boot, when the whole system is still +low on entropy. -## crypto.privateEncrypt(private_key, buffer) +## crypto.setEngine(engine[, flags]) -See above for details. Has the same API as `crypto.privateDecrypt`. -Default padding is `RSA_PKCS1_PADDING`. +Load and set engine for some/all OpenSSL functions (selected by flags). -## crypto.DEFAULT_ENCODING +`engine` could be either an id or a path to the engine's shared library. -The default encoding to use for functions that can take either strings -or buffers. The default value is `'buffer'`, which makes it default -to using Buffer objects. This is here to make the crypto module more -easily compatible with legacy programs that expected `'binary'` to be -the default encoding. +`flags` is optional and has `ENGINE_METHOD_ALL` value by default. It could take +one of or mix of following flags (defined in `constants` module): -Note that new programs will probably expect buffers, so only use this -as a temporary measure. +* `ENGINE_METHOD_RSA` +* `ENGINE_METHOD_DSA` +* `ENGINE_METHOD_DH` +* `ENGINE_METHOD_RAND` +* `ENGINE_METHOD_ECDH` +* `ENGINE_METHOD_ECDSA` +* `ENGINE_METHOD_CIPHERS` +* `ENGINE_METHOD_DIGESTS` +* `ENGINE_METHOD_STORE` +* `ENGINE_METHOD_PKEY_METH` +* `ENGINE_METHOD_PKEY_ASN1_METH` +* `ENGINE_METHOD_ALL` +* `ENGINE_METHOD_NONE` ## Recent API Changes @@ -768,6 +758,26 @@ default, set the `crypto.DEFAULT_ENCODING` field to 'binary'. Note that new programs will probably expect buffers, so only use this as a temporary measure. +## Caveats + +The crypto module still supports some algorithms which are already +compromised. And the API also allows the use of ciphers and hashes +with a small key size that are considered to be too weak for safe use. + +Users should take full responsibility for selecting the crypto +algorithm and key size according to their security requirements. + +Based on the recommendations of [NIST SP 800-131A]: + +- MD5 and SHA-1 are no longer acceptable where collision resistance is + required such as digital signatures. +- The key used with RSA, DSA and DH algorithms is recommended to have + at least 2048 bits and that of the curve of ECDSA and ECDH at least + 224 bits, to be safe to use for several years. +- The DH groups of `modp1`, `modp2` and `modp5` have a key size + smaller than 2048 bits and are not recommended. + +See the reference for other recommendations and details. [createCipher()]: #crypto_crypto_createcipher_algorithm_password [createCipheriv()]: #crypto_crypto_createcipheriv_algorithm_key_iv @@ -779,3 +789,4 @@ temporary measure. [RFC 3526]: http://www.rfc-editor.org/rfc/rfc3526.txt [crypto.pbkdf2]: #crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback [EVP_BytesToKey]: https://www.openssl.org/docs/crypto/EVP_BytesToKey.html +[NIST SP 800-131A]: http://csrc.nist.gov/publications/nistpubs/800-131A/sp800-131A.pdf From 43f2da04d54f7d3c5325952349dd185b4315cb4b Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 11:30:26 -0500 Subject: [PATCH 08/32] doc: sort dgram alphabetically Reorders, with no contextual changes, the dgram documentation alphabetically. --- doc/api/dgram.markdown | 301 ++++++++++++++++++++--------------------- 1 file changed, 149 insertions(+), 152 deletions(-) diff --git a/doc/api/dgram.markdown b/doc/api/dgram.markdown index 72ea2130581d6b..fce88d0fdc2d2f 100644 --- a/doc/api/dgram.markdown +++ b/doc/api/dgram.markdown @@ -20,66 +20,11 @@ You have to change it to this: s.addMembership('224.0.0.114'); }); - -## dgram.createSocket(type[, callback]) - -* `type` String. Either 'udp4' or 'udp6' -* `callback` Function. Attached as a listener to `message` events. - Optional -* Returns: Socket object - -Creates a datagram Socket of the specified types. Valid types are `udp4` -and `udp6`. - -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 -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 -with `socket.address().address` and `socket.address().port`. - -## dgram.createSocket(options[, callback]) -* `options` Object -* `callback` Function. Attached as a listener to `message` events. -* Returns: Socket object - -The `options` object should contain a `type` field of either `udp4` or `udp6` -and an optional boolean `reuseAddr` field. - -When `reuseAddr` is `true` `socket.bind()` will reuse the address, even if -another process has already bound a socket on it. `reuseAddr` defaults to -`false`. - -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 -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 -with `socket.address().address` and `socket.address().port`. - ## Class: dgram.Socket The dgram Socket class encapsulates the datagram functionality. It should be created via `dgram.createSocket(...)` -### Event: 'message' - -* `msg` Buffer object. The message -* `rinfo` Object. Remote address information - -Emitted when a new datagram is available on a socket. `msg` is a `Buffer` and -`rinfo` is an object with the sender's address information: - - socket.on('message', function(msg, rinfo) { - console.log('Received %d bytes from %s:%d\n', - msg.length, rinfo.address, rinfo.port); - }); - -### Event: 'listening' - -Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets -are created. - ### Event: 'close' Emitted after a socket is closed with `close()`. No new `message` events will be emitted @@ -91,72 +36,38 @@ on this socket. Emitted when an error occurs. -### socket.send(buf, offset, length, port, address[, callback]) - -* `buf` Buffer object or string. Message to be sent -* `offset` Integer. Offset in the buffer where the message starts. -* `length` Integer. Number of bytes in the message. -* `port` Integer. Destination port. -* `address` String. Destination hostname or IP address. -* `callback` Function. Called when the message has been sent. Optional. - -For UDP sockets, the destination port and address must be specified. A string -may be supplied for the `address` parameter, and it will be resolved with DNS. - -If the address is omitted or is an empty string, `'0.0.0.0'` or `'::0'` is used -instead. Depending on the network configuration, those defaults may or may not -work; it's best to be explicit about the destination address. +### Event: 'listening' -If the socket has not been previously bound with a call to `bind`, it gets -assigned a random port number and is bound to the "all interfaces" address -(`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) +Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets +are created. -An optional callback may be specified to detect DNS errors or for determining -when it's safe to reuse the `buf` object. Note that DNS lookups delay the time -to send for at least one tick. The only way to know for sure that the datagram -has been sent is by using a callback. If an error occurs and a callback is -given, the error will be the first argument to the callback. If a callback is -not given, the error is emitted as an `'error'` event on the `socket` object. +### Event: 'message' -With consideration for multi-byte characters, `offset` and `length` will -be calculated with respect to -[byte length](buffer.html#buffer_class_method_buffer_bytelength_string_encoding) -and not the character position. +* `msg` Buffer object. The message +* `rinfo` Object. Remote address information -Example of sending a UDP packet to a random port on `localhost`; +Emitted when a new datagram is available on a socket. `msg` is a `Buffer` and +`rinfo` is an object with the sender's address information: - var dgram = require('dgram'); - var message = new Buffer("Some bytes"); - var client = dgram.createSocket("udp4"); - client.send(message, 0, message.length, 41234, "localhost", function(err) { - client.close(); + socket.on('message', function(msg, rinfo) { + console.log('Received %d bytes from %s:%d\n', + msg.length, rinfo.address, rinfo.port); }); -**A Note about UDP datagram size** +### socket.addMembership(multicastAddress[, multicastInterface]) -The maximum size of an `IPv4/v6` datagram depends on the `MTU` (_Maximum Transmission Unit_) -and on the `Payload Length` field size. +* `multicastAddress` String +* `multicastInterface` String, Optional -- The `Payload Length` field is `16 bits` wide, which means that a normal payload - cannot be larger than 64K octets including internet header and data - (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); - this is generally true for loopback interfaces, but such long datagrams - are impractical for most hosts and networks. +Tells the kernel to join a multicast group with `IP_ADD_MEMBERSHIP` socket option. -- The `MTU` is the largest size a given link layer technology can support for datagrams. - For any link, `IPv4` mandates a minimum `MTU` of `68` octets, while the recommended `MTU` - for IPv4 is `576` (typically recommended as the `MTU` for dial-up type applications), - whether they arrive whole or in fragments. +If `multicastInterface` is not specified, the OS will try to add membership to all valid +interfaces. - For `IPv6`, the minimum `MTU` is `1280` octets, however, the mandatory minimum - fragment reassembly buffer size is `1500` octets. - The value of `68` octets is very small, since most current link layer technologies have - a minimum `MTU` of `1500` (like Ethernet). +### socket.address() -Note that it's impossible to know in advance the MTU of each link through which -a packet might travel, and that generally sending a datagram greater than -the (receiver) `MTU` won't work (the packet gets silently dropped, without -informing the source that the data did not reach its intended recipient). +Returns an object containing the address information for a socket. For UDP sockets, +this object will contain `address` , `family` and `port`. ### socket.bind([port][, address][, callback]) @@ -204,7 +115,6 @@ Example of a UDP server listening on port 41234: server.bind(41234); // server listening 0.0.0.0:41234 - ### socket.bind(options[, callback]) * `options` {Object} - Required. Supports the following properties: @@ -230,16 +140,90 @@ shown below. exclusive: true }); - ### socket.close([callback]) 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'](#dgram_event_close) event. -### socket.address() +### socket.dropMembership(multicastAddress[, multicastInterface]) -Returns an object containing the address information for a socket. For UDP sockets, -this object will contain `address` , `family` and `port`. +* `multicastAddress` String +* `multicastInterface` String, Optional + +Opposite of `addMembership` - tells the kernel to leave a multicast group with +`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 +this. + +If `multicastInterface` is not specified, the OS will try to drop membership to all valid +interfaces. + +### socket.send(buf, offset, length, port, address[, callback]) + +* `buf` Buffer object or string. Message to be sent +* `offset` Integer. Offset in the buffer where the message starts. +* `length` Integer. Number of bytes in the message. +* `port` Integer. Destination port. +* `address` String. Destination hostname or IP address. +* `callback` Function. Called when the message has been sent. Optional. + +For UDP sockets, the destination port and address must be specified. A string +may be supplied for the `address` parameter, and it will be resolved with DNS. + +If the address is omitted or is an empty string, `'0.0.0.0'` or `'::0'` is used +instead. Depending on the network configuration, those defaults may or may not +work; it's best to be explicit about the destination address. + +If the socket has not been previously bound with a call to `bind`, it gets +assigned a random port number and is bound to the "all interfaces" address +(`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + +An optional callback may be specified to detect DNS errors or for determining +when it's safe to reuse the `buf` object. Note that DNS lookups delay the time +to send for at least one tick. The only way to know for sure that the datagram +has been sent is by using a callback. If an error occurs and a callback is +given, the error will be the first argument to the callback. If a callback is +not given, the error is emitted as an `'error'` event on the `socket` object. + +With consideration for multi-byte characters, `offset` and `length` will +be calculated with respect to +[byte length](buffer.html#buffer_class_method_buffer_bytelength_string_encoding) +and not the character position. + +Example of sending a UDP packet to a random port on `localhost`; + + var dgram = require('dgram'); + var message = new Buffer("Some bytes"); + var client = dgram.createSocket("udp4"); + client.send(message, 0, message.length, 41234, "localhost", function(err) { + client.close(); + }); + +**A Note about UDP datagram size** + +The maximum size of an `IPv4/v6` datagram depends on the `MTU` (_Maximum Transmission Unit_) +and on the `Payload Length` field size. + +- The `Payload Length` field is `16 bits` wide, which means that a normal payload + cannot be larger than 64K octets including internet header and data + (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); + this is generally true for loopback interfaces, but such long datagrams + are impractical for most hosts and networks. + +- The `MTU` is the largest size a given link layer technology can support for datagrams. + For any link, `IPv4` mandates a minimum `MTU` of `68` octets, while the recommended `MTU` + for IPv4 is `576` (typically recommended as the `MTU` for dial-up type applications), + whether they arrive whole or in fragments. + + For `IPv6`, the minimum `MTU` is `1280` octets, however, the mandatory minimum + fragment reassembly buffer size is `1500` octets. + The value of `68` octets is very small, since most current link layer technologies have + a minimum `MTU` of `1500` (like Ethernet). + +Note that it's impossible to know in advance the MTU of each link through which +a packet might travel, and that generally sending a datagram greater than +the (receiver) `MTU` won't work (the packet gets silently dropped, without +informing the source that the data did not reach its intended recipient). ### socket.setBroadcast(flag) @@ -248,18 +232,12 @@ this object will contain `address` , `family` and `port`. Sets or clears the `SO_BROADCAST` socket option. When this option is set, UDP packets may be sent to a local interface's broadcast address. -### socket.setTTL(ttl) - -* `ttl` Integer +### socket.setMulticastLoopback(flag) -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 -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 -probes or when multicasting. +* `flag` Boolean -The argument to `setTTL()` is a number of hops between 1 and 255. The default on most -systems is 64. +Sets or clears the `IP_MULTICAST_LOOP` socket option. When this option is set, multicast +packets will also be received on the local interface. ### socket.setMulticastTTL(ttl) @@ -273,35 +251,26 @@ decrements the TTL. If the TTL is decremented to 0 by a router, it will not be f The argument to `setMulticastTTL()` is a number of hops between 0 and 255. The default on most systems is 1. -### socket.setMulticastLoopback(flag) - -* `flag` Boolean - -Sets or clears the `IP_MULTICAST_LOOP` socket option. When this option is set, multicast -packets will also be received on the local interface. - -### socket.addMembership(multicastAddress[, multicastInterface]) - -* `multicastAddress` String -* `multicastInterface` String, Optional +### socket.setTTL(ttl) -Tells the kernel to join a multicast group with `IP_ADD_MEMBERSHIP` socket option. +* `ttl` Integer -If `multicastInterface` is not specified, the OS will try to add membership to all valid -interfaces. +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 +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 +probes or when multicasting. -### socket.dropMembership(multicastAddress[, multicastInterface]) +The argument to `setTTL()` is a number of hops between 1 and 255. The default on most +systems is 64. -* `multicastAddress` String -* `multicastInterface` String, Optional +### socket.ref() -Opposite of `addMembership` - tells the kernel to leave a multicast group with -`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 -this. +Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not* +let the program exit if it's the only socket left (the default behavior). If +the socket is `ref`d calling `ref` again will have no effect. -If `multicastInterface` is not specified, the OS will try to drop membership to all valid -interfaces. +Returns `socket`. ### socket.unref() @@ -311,10 +280,38 @@ active socket in the event system. If the socket is already `unref`d calling Returns `socket`. -### socket.ref() +## dgram.createSocket(options[, callback]) +* `options` Object +* `callback` Function. Attached as a listener to `message` events. +* Returns: Socket object -Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not* -let the program exit if it's the only socket left (the default behavior). If -the socket is `ref`d calling `ref` again will have no effect. +The `options` object should contain a `type` field of either `udp4` or `udp6` +and an optional boolean `reuseAddr` field. -Returns `socket`. +When `reuseAddr` is `true` `socket.bind()` will reuse the address, even if +another process has already bound a socket on it. `reuseAddr` defaults to +`false`. + +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 +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 +with `socket.address().address` and `socket.address().port`. + +## dgram.createSocket(type[, callback]) + +* `type` String. Either 'udp4' or 'udp6' +* `callback` Function. Attached as a listener to `message` events. + Optional +* Returns: Socket object + +Creates a datagram Socket of the specified types. Valid types are `udp4` +and `udp6`. + +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 +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 +with `socket.address().address` and `socket.address().port`. From b85d3ac0e346d725d447496e83da024189d61624 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 11:37:27 -0500 Subject: [PATCH 09/32] doc: sort errors alphabetically Reorders, with no contextual changes, the errors documentation alphabetically. --- doc/api/errors.markdown | 432 ++++++++++++++++++++-------------------- 1 file changed, 216 insertions(+), 216 deletions(-) diff --git a/doc/api/errors.markdown b/doc/api/errors.markdown index 505241fc89a487..5e5f9acb99fc57 100644 --- a/doc/api/errors.markdown +++ b/doc/api/errors.markdown @@ -18,6 +18,123 @@ The style of API called determines how generated errors are handed back, or the error. Exceptions can be intercepted using the `try / catch` construct; other propagation strategies are covered [below](#errors_error_propagation_and_interception). +## Error Propagation and Interception + + + +All Node.js APIs will treat invalid arguments as exceptional -- that is, if passed +invalid arguments, they will *immediately* generate and throw the error as an +exception, even if they are an otherwise asynchronous API. + +Synchronous APIs (like +[fs.readFileSync](fs.html#fs_fs_readfilesync_filename_options)) will throw the +error. The act of *throwing* a value (in this case, the error) turns the value +into an **exception**. Exceptions may be caught using the `try { } catch(err) +{ }` construct. + +Asynchronous APIs have **two** mechanisms for error propagation; one mechanism +for APIs that represent a single operation, and one for APIs that represent +multiple operations over time. + +### Error events + + + +The other mechanism for providing errors is the "error" event. This is +typically used by [stream-based](stream.html) and [event emitter-based](events.html#events_class_events_eventemitter) APIs, which +themselves represent a series of asynchronous operations over time (versus a +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, +it will crash the process as an unhandled exception unless [domains](domain.html) are +employed appropriately or [process.on('uncaughtException')](process.html#process_event_uncaughtexception) has a handler. + +```javascript +var net = require('net'); + +var connection = net.connect('localhost'); + +// adding an "error" event handler to a stream: +connection.on('error', function(err) { + // if the connection is reset by the server, or if it can't + // connect at all, or on any sort of error encountered by + // the connection, the error will be sent here. + console.error(err); +}); + +connection.pipe(process.stdout); +``` + +The "throw when no error handlers are attached behavior" is not limited to APIs +provided by Node.js -- even user created event emitters and streams will throw +errors when no error handlers are attached. An example: + +```javascript +var EventEmitter = require('events'); + +var ee = new EventEmitter(); + +setImmediate(function() { + // this will crash the process because no "error" event + // handler has been added. + ee.emit('error', new Error('This will crash')); +}); +``` + +As with node style callbacks, errors generated this way *cannot* be intercepted +by `try { } catch(err) { }` -- they happen *after* the calling code has already +exited. + +### Node style callbacks + + + +Single operation APIs take "node style callbacks" -- a +function provided to the API as an argument. The node style callback takes +at least **one** argument -- `error` -- that will either be `null` (if no error +was encountered) or an `Error` instance. For instance: + +```javascript +var fs = require('fs'); + +fs.readFile('/some/file/that/does-not-exist', function nodeStyleCallback(err, data) { + console.log(err) // Error: ENOENT + console.log(data) // undefined / null +}); + +fs.readFile('/some/file/that/does-exist', function(err, data) { + console.log(err) // null + console.log(data) // +}) +``` + +Note that `try { } catch(err) { }` **cannot** intercept errors generated by +asynchronous APIs. A common mistake for beginners is to try to use `throw` +inside their node style callback: + +```javascript +// THIS WILL NOT WORK: +var fs = require('fs'); + +try { + fs.readFile('/some/file/that/does-not-exist', function(err, data) { + // mistaken assumption: throwing here... + if (err) { + throw err; + } + }); +} catch(err) { + // ... will be caught here -- this is incorrect! + console.log(err); // Error: ENOENT +} +``` + +This will not work! By the time the node style callback has been called, the +surrounding code (including the `try { } catch(err) { }` will have already +exited. Throwing an error inside a node style callback **will crash the process** in most cases. +If [domains](domain.html) are enabled, they may intercept the thrown error; similarly, if a +handler has been added to `process.on('uncaughtException')`, it will intercept +the error. + ## JavaScript Errors @@ -45,6 +162,54 @@ was called. Stack traces are subject to [V8's stack trace API](https://code.goog Stack traces only extend to the beginning of synchronous code execution, *or* a number of frames given by `Error.stackTraceLimit`, whichever is smaller. +#### Error.captureStackTrace(targetObject[, constructorOpt]) + +Creates a `.stack` property on `targetObject`, which when accessed returns +a string representing the location in the program at which `Error.captureStackTrace` +was called. + +```javascript +var myObject = {}; + +Error.captureStackTrace(myObject); + +myObject.stack // similar to `new Error().stack` +``` + +The first line of the trace, instead of being prefixed with `ErrorType: +message`, will be the result of `targetObject.toString()`. + +`constructorOpt` optionally accepts a function. If given, all frames above +`constructorOpt`, including `constructorOpt`, will be omitted from the generated +stack trace. + +This is useful for hiding implementation details of error generation from the +end user. A common way of using this parameter is to pass the current Error +constructor to it: + +```javascript + +function MyError() { + Error.captureStackTrace(this, MyError); +} + +// without passing MyError to captureStackTrace, the MyError +// frame would should up in the .stack property. by passing +// the constructor, we omit that frame and all frames above it. +new MyError().stack + +``` + +#### Error.stackTraceLimit + +Property that determines the number of stack frames collected by a stack trace +(whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). + +The initial value is `10`. It may be set to any valid JavaScript number, which +will affect any stack trace captured *after* the value has been changed. If set +to a non-number value, stack traces will not capture any frames and will report +`undefined` on access. + #### error.message A string of the value passed to `Error()` upon instantiation. The message will @@ -119,54 +284,6 @@ loop tick. System-level errors are generated as augmented Error instances, which are detailed [below](#errors_system_errors). -#### Error.captureStackTrace(targetObject[, constructorOpt]) - -Creates a `.stack` property on `targetObject`, which when accessed returns -a string representing the location in the program at which `Error.captureStackTrace` -was called. - -```javascript -var myObject = {}; - -Error.captureStackTrace(myObject); - -myObject.stack // similar to `new Error().stack` -``` - -The first line of the trace, instead of being prefixed with `ErrorType: -message`, will be the result of `targetObject.toString()`. - -`constructorOpt` optionally accepts a function. If given, all frames above -`constructorOpt`, including `constructorOpt`, will be omitted from the generated -stack trace. - -This is useful for hiding implementation details of error generation from the -end user. A common way of using this parameter is to pass the current Error -constructor to it: - -```javascript - -function MyError() { - Error.captureStackTrace(this, MyError); -} - -// without passing MyError to captureStackTrace, the MyError -// frame would should up in the .stack property. by passing -// the constructor, we omit that frame and all frames above it. -new MyError().stack - -``` - -#### Error.stackTraceLimit - -Property that determines the number of stack frames collected by a stack trace -(whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). - -The initial value is `10`. It may be set to any valid JavaScript number, which -will affect any stack trace captured *after* the value has been changed. If set -to a non-number value, stack traces will not capture any frames and will report -`undefined` on access. - ### Class: RangeError A subclass of Error that indicates that a provided argument was not within the @@ -180,19 +297,6 @@ require('net').connect(-1); // throws RangeError, port should be > 0 && < 65536 Node.js will generate and throw RangeError instances *immediately* -- they are a form of argument validation. -### Class: TypeError - -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 -be considered a TypeError. - -```javascript -require('url').parse(function() { }); // throws TypeError, since it expected a string -``` - -Node.js will generate and throw TypeError instances *immediately* -- they are a form -of argument validation. - ### Class: ReferenceError A subclass of Error that indicates that an attempt is being made to access a variable @@ -238,6 +342,19 @@ try { SyntaxErrors are unrecoverable from the context that created them – they may only be caught by other contexts. +### Class: TypeError + +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 +be considered a TypeError. + +```javascript +require('url').parse(function() { }); // throws TypeError, since it expected a string +``` + +Node.js will generate and throw TypeError instances *immediately* -- they are a form +of argument validation. + ### Exceptions vs. Errors @@ -262,46 +379,49 @@ subclasses, but instead an error instance with added members. ### Class: System Error -#### error.syscall - -A string representing the [syscall](http://man7.org/linux/man-pages/man2/syscall.2.html) that failed. - -#### error.errno #### error.code +#### error.errno A string representing the error code, which is always `E` followed by capital letters, and may be referenced in `man 2 intro`. +#### error.syscall + +A string representing the [syscall](http://man7.org/linux/man-pages/man2/syscall.2.html) that failed. + ### Common System Errors This list is **not exhaustive**, but enumerates many of the common system errors when writing a Node.js program. An exhaustive list may be found [here](http://man7.org/linux/man-pages/man3/errno.3.html). -#### EPERM: Operation not permitted +#### EACCES: Permission denied -An attempt was made to perform an operation that requires appropriate -privileges. +An attempt was made to access a file in a way forbidden by its file access +permissions. -#### ENOENT: No such file or directory +#### EADDRINUSE: Address already in use -Commonly raised by [fs](fs.html) operations; a component of the specified pathname -does not exist -- no entity (file or directory) could be found by the given path. +An attempt to bind a server ([net](net.html), [http](http.html), or [https](https.html)) to a local +address failed due to another server on the local system already occupying +that address. -#### EACCES: Permission denied +#### ECONNREFUSED: Connection refused -An attempt was made to access a file in a way forbidden by its file access -permissions. +No connection could be made because the target machine actively refused +it. This usually results from trying to connect to a service that is inactive +on the foreign host. + +#### ECONNRESET: Connection reset by peer + +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 +or reboot. Commonly encountered via the [http](http.html) and [net](net.html) modules. #### EEXIST: File exists An existing file was the target of an operation that required that the target not exist. -#### ENOTDIR: Not a directory - -A component of the given pathname existed, but was not a directory as expected. -Commonly raised by [fs.readdir](fs.html#fs_fs_readdir_path_callback). - #### EISDIR: Is a directory An operation expected a file, but the given pathname was a directory. @@ -317,154 +437,34 @@ on systems (in particular, OS X) where there is a low file descriptor limit for processes. To remedy a low limit, run `ulimit -n 2048` in the same shell that will run the Node.js process. -#### EPIPE: Broken pipe +#### ENOENT: No such file or directory -A write on a pipe, socket, or FIFO for which there is no process to read the -data. Commonly encountered at the [net](net.html) and [http](http.html) layers, indicative that -the remote side of the stream being written to has been closed. +Commonly raised by [fs](fs.html) operations; a component of the specified pathname +does not exist -- no entity (file or directory) could be found by the given path. -#### EADDRINUSE: Address already in use +#### ENOTDIR: Not a directory -An attempt to bind a server ([net](net.html), [http](http.html), or [https](https.html)) to a local -address failed due to another server on the local system already occupying -that address. +A component of the given pathname existed, but was not a directory as expected. +Commonly raised by [fs.readdir](fs.html#fs_fs_readdir_path_callback). -#### ECONNRESET: Connection reset by peer +#### ENOTEMPTY: Directory not empty -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 -or reboot. Commonly encountered via the [http](http.html) and [net](net.html) modules. +A directory with entries was the target of an operation that requires +an empty directory -- usually [fs.unlink](fs.html#fs_fs_unlink_path_callback). -#### ECONNREFUSED: Connection refused +#### EPERM: Operation not permitted -No connection could be made because the target machine actively refused -it. This usually results from trying to connect to a service that is inactive -on the foreign host. +An attempt was made to perform an operation that requires appropriate +privileges. -#### ENOTEMPTY: Directory not empty +#### EPIPE: Broken pipe -A directory with entries was the target of an operation that requires -an empty directory -- usually [fs.unlink](fs.html#fs_fs_unlink_path_callback). +A write on a pipe, socket, or FIFO for which there is no process to read the +data. Commonly encountered at the [net](net.html) and [http](http.html) layers, indicative that +the remote side of the stream being written to has been closed. #### ETIMEDOUT: Operation timed out A connect or send request failed because the connected party did not properly respond after a period of time. Usually encountered by [http](http.html) or [net](net.html) -- often a sign that a connected socket was not `.end()`'d appropriately. - -## Error Propagation and Interception - - - -All Node.js APIs will treat invalid arguments as exceptional -- that is, if passed -invalid arguments, they will *immediately* generate and throw the error as an -exception, even if they are an otherwise asynchronous API. - -Synchronous APIs (like -[fs.readFileSync](fs.html#fs_fs_readfilesync_filename_options)) will throw the -error. The act of *throwing* a value (in this case, the error) turns the value -into an **exception**. Exceptions may be caught using the `try { } catch(err) -{ }` construct. - -Asynchronous APIs have **two** mechanisms for error propagation; one mechanism -for APIs that represent a single operation, and one for APIs that represent -multiple operations over time. - -### Node style callbacks - - - -Single operation APIs take "node style callbacks" -- a -function provided to the API as an argument. The node style callback takes -at least **one** argument -- `error` -- that will either be `null` (if no error -was encountered) or an `Error` instance. For instance: - -```javascript -var fs = require('fs'); - -fs.readFile('/some/file/that/does-not-exist', function nodeStyleCallback(err, data) { - console.log(err) // Error: ENOENT - console.log(data) // undefined / null -}); - -fs.readFile('/some/file/that/does-exist', function(err, data) { - console.log(err) // null - console.log(data) // -}) -``` - -Note that `try { } catch(err) { }` **cannot** intercept errors generated by -asynchronous APIs. A common mistake for beginners is to try to use `throw` -inside their node style callback: - -```javascript -// THIS WILL NOT WORK: -var fs = require('fs'); - -try { - fs.readFile('/some/file/that/does-not-exist', function(err, data) { - // mistaken assumption: throwing here... - if (err) { - throw err; - } - }); -} catch(err) { - // ... will be caught here -- this is incorrect! - console.log(err); // Error: ENOENT -} -``` - -This will not work! By the time the node style callback has been called, the -surrounding code (including the `try { } catch(err) { }` will have already -exited. Throwing an error inside a node style callback **will crash the process** in most cases. -If [domains](domain.html) are enabled, they may intercept the thrown error; similarly, if a -handler has been added to `process.on('uncaughtException')`, it will intercept -the error. - -### Error events - - - -The other mechanism for providing errors is the "error" event. This is -typically used by [stream-based](stream.html) and [event emitter-based](events.html#events_class_events_eventemitter) APIs, which -themselves represent a series of asynchronous operations over time (versus a -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, -it will crash the process as an unhandled exception unless [domains](domain.html) are -employed appropriately or [process.on('uncaughtException')](process.html#process_event_uncaughtexception) has a handler. - -```javascript -var net = require('net'); - -var connection = net.connect('localhost'); - -// adding an "error" event handler to a stream: -connection.on('error', function(err) { - // if the connection is reset by the server, or if it can't - // connect at all, or on any sort of error encountered by - // the connection, the error will be sent here. - console.error(err); -}); - -connection.pipe(process.stdout); -``` - -The "throw when no error handlers are attached behavior" is not limited to APIs -provided by Node.js -- even user created event emitters and streams will throw -errors when no error handlers are attached. An example: - -```javascript -var EventEmitter = require('events'); - -var ee = new EventEmitter(); - -setImmediate(function() { - // this will crash the process because no "error" event - // handler has been added. - ee.emit('error', new Error('This will crash')); -}); -``` - -As with node style callbacks, errors generated this way *cannot* be intercepted -by `try { } catch(err) { }` -- they happen *after* the calling code has already -exited. From 03129f850f3a2f9aeffd198b05cca158dfe1db10 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 11:45:27 -0500 Subject: [PATCH 10/32] doc: sort events alphabetically Reorders, with minimal contextual duplication, the events documentation alphabetically. --- doc/api/events.markdown | 191 +++++++++++++++++++++------------------- 1 file changed, 100 insertions(+), 91 deletions(-) diff --git a/doc/api/events.markdown b/doc/api/events.markdown index 543d263dc3d799..d111e05706d186 100644 --- a/doc/api/events.markdown +++ b/doc/api/events.markdown @@ -34,68 +34,81 @@ a stack trace and exit the program. All EventEmitters emit the event `'newListener'` when new listeners are added and `'removeListener'` when a listener is removed. -### emitter.addListener(event, listener) -### emitter.on(event, listener) +### Inheriting from 'EventEmitter' -Adds a listener to the end of the listeners array for the specified `event`. -No checks are made to see if the `listener` has already been added. Multiple -calls passing the same combination of `event` and `listener` will result in the -`listener` being added multiple times. +Inheriting from `EventEmitter` is no different from inheriting from any other +constructor function. For example: - server.on('connection', function (stream) { - console.log('someone connected!'); - }); + 'use strict'; + const util = require('util'); + const EventEmitter = require('events'); -Returns emitter, so calls can be chained. + function MyEventEmitter() { + // Initialize necessary properties from `EventEmitter` in this instance + EventEmitter.call(this); + } -### emitter.once(event, listener) + // Inherit functions from `EventEmitter`'s prototype + util.inherits(MyEventEmitter, EventEmitter); -Adds a **one time** listener for the event. This listener is -invoked only the next time the event is fired, after which -it is removed. - server.once('connection', function (stream) { - console.log('Ah, we have our first user!'); - }); +[emitter.listenerCount]: #events_emitter_listenercount_type -Returns emitter, so calls can be chained. +### Class Method: EventEmitter.listenerCount(emitter, event) -### emitter.removeListener(event, listener) + Stability: 0 - Deprecated: Use [emitter.listenerCount][] instead. -Removes a listener from the listener array for the specified event. -**Caution**: changes array indices in the listener array behind the listener. +Returns the number of listeners for a given event. - var callback = function(stream) { - console.log('someone connected!'); - }; - server.on('connection', callback); - // ... - server.removeListener('connection', callback); +### Event: 'newListener' -`removeListener` will remove, at most, one instance of a listener from the -listener array. If any single listener has been added multiple times to the -listener array for the specified `event`, then `removeListener` must be called -multiple times to remove each instance. +* `event` {String} The event name +* `listener` {Function} The event handler function -Returns emitter, so calls can be chained. +This event is emitted *before* a listener is added. When this event is +triggered, the listener has not been added to the array of listeners for the +`event`. Any listeners added to the event `name` in the newListener event +callback will be added *before* the listener that is in the process of being +added. -### emitter.removeAllListeners([event]) -Removes all listeners, or those of the specified event. It's not a good idea to -remove listeners that were added elsewhere in the code, especially when it's on -an emitter that you didn't create (e.g. sockets or file streams). +### Event: 'removeListener' -Returns emitter, so calls can be chained. +* `event` {String} The event name +* `listener` {Function} The event handler function -### emitter.setMaxListeners(n) +This event is emitted *after* a listener is removed. When this event is +triggered, the listener has been removed from the array of listeners for the +`event`. -By default EventEmitters will print a warning if more than 10 listeners are -added for a particular event. This is a useful default which helps finding -memory leaks. Obviously not all Emitters should be limited to 10. This function -allows that to be increased. Set to `Infinity` (or `0`) for unlimited. +### EventEmitter.defaultMaxListeners + +`emitter.setMaxListeners(n)` sets the maximum on a per-instance basis. +This class property lets you set it for *all* `EventEmitter` instances, +current and future, effective immediately. Use with care. + +Note that `emitter.setMaxListeners(n)` still has precedence over +`EventEmitter.defaultMaxListeners`. + +### emitter.addListener(event, listener) + +Adds a listener to the end of the listeners array for the specified `event`. +No checks are made to see if the `listener` has already been added. Multiple +calls passing the same combination of `event` and `listener` will result in the +`listener` being added multiple times. + + server.addListener('connection', function (stream) { + console.log('someone connected!'); + }); Returns emitter, so calls can be chained. +### emitter.emit(event[, arg1][, arg2][, ...]) + +Calls each of the listeners in order with the supplied arguments. + +Returns `true` if event had listeners, `false` otherwise. + ### emitter.getMaxListeners() Returns the current max listener value for the emitter which is either set by @@ -110,15 +123,11 @@ while not being irresponsible and setting a too big number. emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); }); -### EventEmitter.defaultMaxListeners - -`emitter.setMaxListeners(n)` sets the maximum on a per-instance basis. -This class property lets you set it for *all* `EventEmitter` instances, -current and future, effective immediately. Use with care. +### emitter.listenerCount(type) -Note that `emitter.setMaxListeners(n)` still has precedence over -`EventEmitter.defaultMaxListeners`. +* `type` {Value} The type of event +Returns the number of listeners listening to the `type` of event. ### emitter.listeners(event) @@ -129,63 +138,63 @@ Returns a copy of the array of listeners for the specified event. }); console.log(util.inspect(server.listeners('connection'))); // [ [Function] ] +### emitter.on(event, listener) -### emitter.emit(event[, arg1][, arg2][, ...]) - -Calls each of the listeners in order with the supplied arguments. - -Returns `true` if event had listeners, `false` otherwise. - - -### emitter.listenerCount(type) - -* `type` {Value} The type of event - -Returns the number of listeners listening to the `type` of event. +Adds a listener to the end of the listeners array for the specified `event`. +No checks are made to see if the `listener` has already been added. Multiple +calls passing the same combination of `event` and `listener` will result in the +`listener` being added multiple times. -### Class Method: EventEmitter.listenerCount(emitter, event) + server.on('connection', function (stream) { + console.log('someone connected!'); + }); - Stability: 0 - Deprecated: Use [emitter.listenerCount][] instead. +Returns emitter, so calls can be chained. -Returns the number of listeners for a given event. +### emitter.once(event, listener) -### Event: 'newListener' +Adds a **one time** listener for the event. This listener is +invoked only the next time the event is fired, after which +it is removed. -* `event` {String} The event name -* `listener` {Function} The event handler function + server.once('connection', function (stream) { + console.log('Ah, we have our first user!'); + }); -This event is emitted *before* a listener is added. When this event is -triggered, the listener has not been added to the array of listeners for the -`event`. Any listeners added to the event `name` in the newListener event -callback will be added *before* the listener that is in the process of being -added. +Returns emitter, so calls can be chained. +### emitter.removeAllListeners([event]) -### Event: 'removeListener' +Removes all listeners, or those of the specified event. It's not a good idea to +remove listeners that were added elsewhere in the code, especially when it's on +an emitter that you didn't create (e.g. sockets or file streams). -* `event` {String} The event name -* `listener` {Function} The event handler function +Returns emitter, so calls can be chained. -This event is emitted *after* a listener is removed. When this event is -triggered, the listener has been removed from the array of listeners for the -`event`. +### emitter.removeListener(event, listener) -### Inheriting from 'EventEmitter' +Removes a listener from the listener array for the specified event. +**Caution**: changes array indices in the listener array behind the listener. -Inheriting from `EventEmitter` is no different from inheriting from any other -constructor function. For example: + var callback = function(stream) { + console.log('someone connected!'); + }; + server.on('connection', callback); + // ... + server.removeListener('connection', callback); - 'use strict'; - const util = require('util'); - const EventEmitter = require('events'); +`removeListener` will remove, at most, one instance of a listener from the +listener array. If any single listener has been added multiple times to the +listener array for the specified `event`, then `removeListener` must be called +multiple times to remove each instance. - function MyEventEmitter() { - // Initialize necessary properties from `EventEmitter` in this instance - EventEmitter.call(this); - } +Returns emitter, so calls can be chained. - // Inherit functions from `EventEmitter`'s prototype - util.inherits(MyEventEmitter, EventEmitter); +### emitter.setMaxListeners(n) +By default EventEmitters will print a warning if more than 10 listeners are +added for a particular event. This is a useful default which helps finding +memory leaks. Obviously not all Emitters should be limited to 10. This function +allows that to be increased. Set to `Infinity` (or `0`) for unlimited. -[emitter.listenerCount]: #events_emitter_listenercount_type +Returns emitter, so calls can be chained. From c44523a1c02ac82bcfae386c2ea0edd80afa2294 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:07:07 -0500 Subject: [PATCH 11/32] doc: sort fs alphabetically Reorders, with no contextual changes, the fs documentation alphabetically. --- doc/api/fs.markdown | 996 ++++++++++++++++++++++---------------------- 1 file changed, 496 insertions(+), 500 deletions(-) diff --git a/doc/api/fs.markdown b/doc/api/fs.markdown index b46c94984fbca8..d5e3a9d2711e6f 100644 --- a/doc/api/fs.markdown +++ b/doc/api/fs.markdown @@ -84,218 +84,397 @@ site, set the NODE_DEBUG environment variable: at Object. (/path/to/script.js:5:1) +## Class: fs.FSWatcher -## fs.rename(oldPath, newPath, callback) +Objects returned from `fs.watch()` are of this type. -Asynchronous rename(2). No arguments other than a possible exception are given -to the completion callback. +### Event: 'change' -## fs.renameSync(oldPath, newPath) +* `event` {String} The type of fs change +* `filename` {String} The filename that changed (if relevant/available) -Synchronous rename(2). Returns `undefined`. +Emitted when something changes in a watched directory or file. +See more details in [fs.watch](#fs_fs_watch_filename_options_listener). -## fs.ftruncate(fd, len, callback) +### Event: 'error' -Asynchronous ftruncate(2). No arguments other than a possible exception are -given to the completion callback. +* `error` {Error object} -## fs.ftruncateSync(fd, len) +Emitted when an error occurs. -Synchronous ftruncate(2). Returns `undefined`. +### watcher.close() -## fs.truncate(path, len, callback) +Stop watching for changes on the given `fs.FSWatcher`. -Asynchronous truncate(2). No arguments other than a possible exception are -given to the completion callback. A file descriptor can also be passed as the -first argument. In this case, `fs.ftruncate()` is called. +## Class: fs.ReadStream -## fs.truncateSync(path, len) +`ReadStream` is a [Readable Stream](stream.html#stream_class_stream_readable). -Synchronous truncate(2). Returns `undefined`. +### Event: 'open' -## fs.chown(path, uid, gid, callback) +* `fd` {Integer} file descriptor used by the ReadStream. -Asynchronous chown(2). No arguments other than a possible exception are given -to the completion callback. +Emitted when the ReadStream's file is opened. -## fs.chownSync(path, uid, gid) +## Class: fs.Stats -Synchronous chown(2). Returns `undefined`. +Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their +synchronous counterparts are of this type. -## fs.fchown(fd, uid, gid, callback) + - `stats.isFile()` + - `stats.isDirectory()` + - `stats.isBlockDevice()` + - `stats.isCharacterDevice()` + - `stats.isSymbolicLink()` (only valid with `fs.lstat()`) + - `stats.isFIFO()` + - `stats.isSocket()` -Asynchronous fchown(2). No arguments other than a possible exception are given -to the completion callback. +For a regular file `util.inspect(stats)` would return a string very +similar to this: -## fs.fchownSync(fd, uid, gid) + { dev: 2114, + ino: 48064969, + mode: 33188, + nlink: 1, + uid: 85, + gid: 100, + rdev: 0, + size: 527, + blksize: 4096, + blocks: 8, + atime: Mon, 10 Oct 2011 23:24:11 GMT, + mtime: Mon, 10 Oct 2011 23:24:11 GMT, + ctime: Mon, 10 Oct 2011 23:24:11 GMT, + birthtime: Mon, 10 Oct 2011 23:24:11 GMT } -Synchronous fchown(2). Returns `undefined`. +Please note that `atime`, `mtime`, `birthtime`, and `ctime` are +instances of [Date][MDN-Date] object and to compare the values of +these objects you should use appropriate methods. For most general +uses [getTime()][MDN-Date-getTime] will return the number of +milliseconds elapsed since _1 January 1970 00:00:00 UTC_ and this +integer should be sufficient for any comparison, however there are +additional methods which can be used for displaying fuzzy information. +More details can be found in the [MDN JavaScript Reference][MDN-Date] +page. -## fs.lchown(path, uid, gid, callback) +[MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date +[MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime -Asynchronous lchown(2). No arguments other than a possible exception are given -to the completion callback. +### Stat Time Values -## fs.lchownSync(path, uid, gid) +The times in the stat object have the following semantics: -Synchronous lchown(2). Returns `undefined`. +* `atime` "Access Time" - Time when file data last accessed. Changed + by the `mknod(2)`, `utimes(2)`, and `read(2)` system calls. +* `mtime` "Modified Time" - Time when file data last modified. + Changed by the `mknod(2)`, `utimes(2)`, and `write(2)` system calls. +* `ctime` "Change Time" - Time when file status was last changed + (inode data modification). Changed by the `chmod(2)`, `chown(2)`, + `link(2)`, `mknod(2)`, `rename(2)`, `unlink(2)`, `utimes(2)`, + `read(2)`, and `write(2)` system calls. +* `birthtime` "Birth Time" - Time of file creation. Set once when the + file is created. On filesystems where birthtime is not available, + this field may instead hold either the `ctime` or + `1970-01-01T00:00Z` (ie, unix epoch timestamp `0`). On Darwin and + other FreeBSD variants, also set if the `atime` is explicitly set to + an earlier value than the current `birthtime` using the `utimes(2)` + system call. -## fs.chmod(path, mode, callback) +Prior to Node v0.12, the `ctime` held the `birthtime` on Windows +systems. Note that as of v0.12, `ctime` is not "creation time", and +on Unix systems, it never was. -Asynchronous chmod(2). No arguments other than a possible exception are given -to the completion callback. +## Class: fs.WriteStream -## fs.chmodSync(path, mode) +`WriteStream` is a [Writable Stream](stream.html#stream_class_stream_writable). -Synchronous chmod(2). Returns `undefined`. +### Event: 'open' -## fs.fchmod(fd, mode, callback) +* `fd` {Integer} file descriptor used by the WriteStream. -Asynchronous fchmod(2). No arguments other than a possible exception -are given to the completion callback. +Emitted when the WriteStream's file is opened. -## fs.fchmodSync(fd, mode) +### file.bytesWritten -Synchronous fchmod(2). Returns `undefined`. +The number of bytes written so far. Does not include data that is still queued +for writing. -## fs.lchmod(path, mode, callback) +## fs.access(path[, mode], callback) -Asynchronous lchmod(2). No arguments other than a possible exception -are given to the completion callback. +Tests a user's permissions for the file specified by `path`. `mode` is an +optional integer that specifies the accessibility checks to be performed. The +following constants define the possible values of `mode`. It is possible to +create a mask consisting of the bitwise OR of two or more values. -Only available on Mac OS X. +- `fs.F_OK` - File is visible to the calling process. This is useful for +determining if a file exists, but says nothing about `rwx` permissions. +Default if no `mode` is specified. +- `fs.R_OK` - File can be read by the calling process. +- `fs.W_OK` - File can be written by the calling process. +- `fs.X_OK` - File can be executed by the calling process. This has no effect +on Windows (will behave like `fs.F_OK`). -## fs.lchmodSync(path, mode) +The final argument, `callback`, is a callback function that is invoked with +a possible error argument. If any of the accessibility checks fail, the error +argument will be populated. The following example checks if the file +`/etc/passwd` can be read and written by the current process. -Synchronous lchmod(2). Returns `undefined`. + fs.access('/etc/passwd', fs.R_OK | fs.W_OK, function (err) { + console.log(err ? 'no access!' : 'can read/write'); + }); -## fs.stat(path, callback) +## fs.accessSync(path[, mode]) -Asynchronous stat(2). The callback gets two arguments `(err, stats)` where -`stats` is a [fs.Stats](#fs_class_fs_stats) object. See the [fs.Stats](#fs_class_fs_stats) -section below for more information. +Synchronous version of `fs.access`. This throws if any accessibility checks +fail, and does nothing otherwise. -## fs.lstat(path, callback) +## fs.appendFile(file, data[, options], callback) -Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where -`stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if -`path` is a symbolic link, then the link itself is stat-ed, not the file that it -refers to. +* `file` {String | Integer} filename or file descriptor +* `data` {String | Buffer} +* `options` {Object | String} + * `encoding` {String | Null} default = `'utf8'` + * `mode` {Number} default = `0o666` + * `flag` {String} default = `'a'` +* `callback` {Function} -## fs.fstat(fd, callback) +Asynchronously append data to a file, creating the file if it does not yet exist. +`data` can be a string or a buffer. -Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where -`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`. +Example: -## fs.statSync(path) + fs.appendFile('message.txt', 'data to append', function (err) { + if (err) throw err; + console.log('The "data to append" was appended to file!'); + }); -Synchronous stat(2). Returns an instance of `fs.Stats`. +If `options` is a string, then it specifies the encoding. Example: -## fs.lstatSync(path) + fs.appendFile('message.txt', 'data to append', 'utf8', callback); -Synchronous lstat(2). Returns an instance of `fs.Stats`. +Any specified file descriptor has to have been opened for appending. -## fs.fstatSync(fd) +_Note: Specified file descriptors will not be closed automatically._ -Synchronous fstat(2). Returns an instance of `fs.Stats`. +## fs.appendFileSync(file, data[, options]) -## fs.link(srcpath, dstpath, callback) +The synchronous version of `fs.appendFile`. Returns `undefined`. -Asynchronous link(2). No arguments other than a possible exception are given to -the completion callback. +## fs.chmod(path, mode, callback) -## fs.linkSync(srcpath, dstpath) +Asynchronous chmod(2). No arguments other than a possible exception are given +to the completion callback. -Synchronous link(2). Returns `undefined`. +## fs.chmodSync(path, mode) -## fs.symlink(destination, path[, type], callback) +Synchronous chmod(2). Returns `undefined`. -Asynchronous symlink(2). No arguments other than a possible exception are given +## fs.chown(path, uid, gid, callback) + +Asynchronous chown(2). No arguments other than a possible exception are given to the completion callback. -The `type` argument can be set to `'dir'`, `'file'`, or `'junction'` (default -is `'file'`) and is only available on Windows (ignored on other platforms). -Note that Windows junction points require the destination path to be absolute. When using -`'junction'`, the `destination` argument will automatically be normalized to absolute path. -## fs.symlinkSync(destination, path[, type]) +## fs.chownSync(path, uid, gid) -Synchronous symlink(2). Returns `undefined`. +Synchronous chown(2). Returns `undefined`. -## fs.readlink(path, callback) +## fs.close(fd, callback) -Asynchronous readlink(2). The callback gets two arguments `(err, -linkString)`. +Asynchronous close(2). No arguments other than a possible exception are given +to the completion callback. -## fs.readlinkSync(path) +## fs.closeSync(fd) -Synchronous readlink(2). Returns the symbolic link's string value. +Synchronous close(2). Returns `undefined`. -## fs.realpath(path[, cache], callback) +## fs.createReadStream(path[, options]) -Asynchronous realpath(2). The `callback` gets two arguments `(err, -resolvedPath)`. May use `process.cwd` to resolve relative paths. `cache` is an -object literal of mapped paths that can be used to force a specific path -resolution or avoid additional `fs.stat` calls for known real paths. +Returns a new ReadStream object (See `Readable Stream`). -Example: +Be aware that, unlike the default value set for `highWaterMark` on a +readable stream (16 kb), the stream returned by this method has a +default value of 64 kb for the same parameter. - var cache = {'/etc':'/private/etc'}; - fs.realpath('/etc/passwd', cache, function (err, resolvedPath) { - if (err) throw err; - console.log(resolvedPath); - }); +`options` is an object or string with the following defaults: -## fs.realpathSync(path[, cache]) + { flags: 'r', + encoding: null, + fd: null, + mode: 0o666, + autoClose: true + } -Synchronous realpath(2). Returns the resolved path. +`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 +start at 0. The `encoding` can be any one of those accepted by [Buffer][]. -## fs.unlink(path, callback) +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. -Asynchronous unlink(2). No arguments other than a possible exception are given -to the completion callback. +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 no file descriptor leak. If `autoClose` is set to true (default +behavior), on `error` or `end` the file descriptor will be closed +automatically. -## fs.unlinkSync(path) +`mode` sets the file mode (permission and sticky bits), but only if the +file was created. -Synchronous unlink(2). Returns `undefined`. +An example to read the last 10 bytes of a file which is 100 bytes long: -## fs.rmdir(path, callback) + fs.createReadStream('sample.txt', {start: 90, end: 99}); -Asynchronous rmdir(2). No arguments other than a possible exception are given +If `options` is a string, then it specifies the encoding. + +## fs.createWriteStream(path[, options]) + +Returns a new WriteStream object (See `Writable Stream`). + +`options` is an object or string with the following defaults: + + { flags: 'w', + defaultEncoding: 'utf8', + fd: null, + mode: 0o666 } + +`options` may also include a `start` option to allow writing data at +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 +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 +`path` argument and will use the specified file descriptor. This means that no +`open` event will be emitted. + +If `options` is a string, then it specifies the encoding. + +## fs.exists(path, callback) + + Stability: 0 - Deprecated: Use [fs.stat][] or [fs.access][] instead. + +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: + + fs.exists('/etc/passwd', function (exists) { + console.log(exists ? "it's there" : 'no passwd!'); + }); + +`fs.exists()` should not be used to check if a file exists before calling +`fs.open()`. Doing so introduces a race condition since other processes may +change the file's state between the two calls. Instead, user code should +call `fs.open()` directly and handle the error raised if the file is +non-existent. + +## fs.existsSync(path) + +Synchronous version of [`fs.exists`](fs.html#fs_fs_exists_path_callback). +Returns `true` if the file exists, `false` otherwise. + + Stability: 0 - Deprecated: Use [fs.statSync][] or [fs.accessSync][] instead. + +## fs.fchmod(fd, mode, callback) + +Asynchronous fchmod(2). No arguments other than a possible exception +are given to the completion callback. + +## fs.fchmodSync(fd, mode) + +Synchronous fchmod(2). Returns `undefined`. + +## fs.fchown(fd, uid, gid, callback) + +Asynchronous fchown(2). No arguments other than a possible exception are given to the completion callback. -## fs.rmdirSync(path) +## fs.fchownSync(fd, uid, gid) -Synchronous rmdir(2). Returns `undefined`. +Synchronous fchown(2). Returns `undefined`. -## fs.mkdir(path[, mode], callback) +## fs.fstat(fd, callback) -Asynchronous mkdir(2). No arguments other than a possible exception are given -to the completion callback. `mode` defaults to `0o777`. +Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where +`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`. -## fs.mkdirSync(path[, mode]) +## fs.fstatSync(fd) -Synchronous mkdir(2). Returns `undefined`. +Synchronous fstat(2). Returns an instance of `fs.Stats`. -## fs.readdir(path, callback) +## fs.fsync(fd, callback) -Asynchronous readdir(3). Reads the contents of a directory. -The callback gets two arguments `(err, files)` where `files` is an array of -the names of the files in the directory excluding `'.'` and `'..'`. +Asynchronous fsync(2). No arguments other than a possible exception are given +to the completion callback. -## fs.readdirSync(path) +## fs.fsyncSync(fd) -Synchronous readdir(3). Returns an array of filenames excluding `'.'` and -`'..'`. +Synchronous fsync(2). Returns `undefined`. -## fs.close(fd, callback) +## fs.ftruncate(fd, len, callback) -Asynchronous close(2). No arguments other than a possible exception are given +Asynchronous ftruncate(2). No arguments other than a possible exception are +given to the completion callback. + +## fs.ftruncateSync(fd, len) + +Synchronous ftruncate(2). Returns `undefined`. + +## fs.futimes(fd, atime, mtime, callback) + +Change the file timestamps of a file referenced by the supplied file +descriptor. + +## fs.futimesSync(fd, atime, mtime) + +Synchronous version of `fs.futimes()`. Returns `undefined`. + +## fs.lchmod(path, mode, callback) + +Asynchronous lchmod(2). No arguments other than a possible exception +are given to the completion callback. + +Only available on Mac OS X. + +## fs.lchmodSync(path, mode) + +Synchronous lchmod(2). Returns `undefined`. + +## fs.lchown(path, uid, gid, callback) + +Asynchronous lchown(2). No arguments other than a possible exception are given to the completion callback. -## fs.closeSync(fd) +## fs.lchownSync(path, uid, gid) -Synchronous close(2). Returns `undefined`. +Synchronous lchown(2). Returns `undefined`. + +## fs.link(srcpath, dstpath, callback) + +Asynchronous link(2). No arguments other than a possible exception are given to +the completion callback. + +## fs.linkSync(srcpath, dstpath) + +Synchronous link(2). Returns `undefined`. + +## fs.lstat(path, callback) + +Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where +`stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if +`path` is a symbolic link, then the link itself is stat-ed, not the file that it +refers to. + +## fs.lstatSync(path) + +Synchronous lstat(2). Returns an instance of `fs.Stats`. + +## fs.mkdir(path[, mode], callback) + +Asynchronous mkdir(2). No arguments other than a possible exception are given +to the completion callback. `mode` defaults to `0o777`. + +## fs.mkdirSync(path[, mode]) + +Synchronous mkdir(2). Returns `undefined`. ## fs.open(path, flags[, mode], callback) @@ -359,255 +538,158 @@ the end of the file. Synchronous version of `fs.open()`. Returns an integer representing the file descriptor. -## fs.utimes(path, atime, mtime, callback) +## fs.read(fd, buffer, offset, length, position, callback) -Change file timestamps of the file referenced by the supplied path. +Read data from the file specified by `fd`. -Note: the arguments `atime` and `mtime` of the following related functions does -follow the below rules: +`buffer` is the buffer that the data will be written to. -- If the value is a numberable string like "123456789", the value would get - converted to corresponding number. -- If the value is `NaN` or `Infinity`, the value would get converted to - `Date.now()`. +`offset` is the offset in the buffer to start writing at. -## fs.utimesSync(path, atime, mtime) +`length` is an integer specifying the number of bytes to read. -Synchronous version of `fs.utimes()`. Returns `undefined`. +`position` is an integer specifying where to begin reading from in the file. +If `position` is `null`, data will be read from the current file position. +The callback is given the three arguments, `(err, bytesRead, buffer)`. -## fs.futimes(fd, atime, mtime, callback) +## fs.readdir(path, callback) -Change the file timestamps of a file referenced by the supplied file -descriptor. +Asynchronous readdir(3). Reads the contents of a directory. +The callback gets two arguments `(err, files)` where `files` is an array of +the names of the files in the directory excluding `'.'` and `'..'`. -## fs.futimesSync(fd, atime, mtime) +## fs.readdirSync(path) -Synchronous version of `fs.futimes()`. Returns `undefined`. +Synchronous readdir(3). Returns an array of filenames excluding `'.'` and +`'..'`. -## fs.fsync(fd, callback) +## fs.readFile(file[, options], callback) -Asynchronous fsync(2). No arguments other than a possible exception are given -to the completion callback. +* `file` {String | Integer} filename or file descriptor +* `options` {Object | String} + * `encoding` {String | Null} default = `null` + * `flag` {String} default = `'r'` +* `callback` {Function} -## fs.fsyncSync(fd) +Asynchronously reads the entire contents of a file. Example: -Synchronous fsync(2). Returns `undefined`. + fs.readFile('/etc/passwd', function (err, data) { + if (err) throw err; + console.log(data); + }); -## fs.write(fd, buffer, offset, length[, position], callback) +The callback is passed two arguments `(err, data)`, where `data` is the +contents of the file. -Write `buffer` to the file specified by `fd`. +If no encoding is specified, then the raw buffer is returned. -`offset` and `length` determine the part of the buffer to be written. +If `options` is a string, then it specifies the encoding. Example: -`position` refers to the offset from the beginning of the file where this data -should be written. If `typeof position !== 'number'`, the data will be written -at the current position. See pwrite(2). + fs.readFile('/etc/passwd', 'utf8', callback); -The callback will be given three arguments `(err, written, buffer)` where -`written` specifies how many _bytes_ were written from `buffer`. +Any specified file descriptor has to support reading. -Note that it is unsafe to use `fs.write` multiple times on the same file -without waiting for the callback. For this scenario, -`fs.createWriteStream` is strongly recommended. +_Note: Specified file descriptors will not be closed automatically._ -On Linux, positional writes don't work when the file is opened in append mode. -The kernel ignores the position argument and always appends the data to -the end of the file. +## fs.readFileSync(file[, options]) -## fs.write(fd, data[, position[, encoding]], callback) +Synchronous version of `fs.readFile`. Returns the contents of the `file`. -Write `data` to the file specified by `fd`. If `data` is not a Buffer instance -then the value will be coerced to a string. +If the `encoding` option is specified then this function returns a +string. Otherwise it returns a buffer. -`position` refers to the offset from the beginning of the file where this data -should be written. If `typeof position !== 'number'` the data will be written at -the current position. See pwrite(2). +## fs.readlink(path, callback) -`encoding` is the expected string encoding. +Asynchronous readlink(2). The callback gets two arguments `(err, +linkString)`. -The callback will receive the arguments `(err, written, string)` where `written` -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](buffer.html#buffer_class_method_buffer_bytelength_string_encoding). +## fs.readSync(fd, buffer, offset, length, position) -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 -be the same as the string offset. +Synchronous version of `fs.read`. Returns the number of `bytesRead`. -Note that it is unsafe to use `fs.write` multiple times on the same file -without waiting for the callback. For this scenario, -`fs.createWriteStream` is strongly recommended. - -On Linux, positional writes don't work when the file is opened in append mode. -The kernel ignores the position argument and always appends the data to -the end of the file. - -## fs.writeSync(fd, buffer, offset, length[, position]) - -## fs.writeSync(fd, data[, position[, encoding]]) - -Synchronous versions of `fs.write()`. Returns the number of bytes written. - -## fs.read(fd, buffer, offset, length, position, callback) - -Read data from the file specified by `fd`. - -`buffer` is the buffer that the data will be written to. - -`offset` is the offset in the buffer to start writing at. - -`length` is an integer specifying the number of bytes to read. - -`position` is an integer specifying where to begin reading from in the file. -If `position` is `null`, data will be read from the current file position. - -The callback is given the three arguments, `(err, bytesRead, buffer)`. - -## fs.readSync(fd, buffer, offset, length, position) - -Synchronous version of `fs.read`. Returns the number of `bytesRead`. - -## fs.readFile(file[, options], callback) - -* `file` {String | Integer} filename or file descriptor -* `options` {Object | String} - * `encoding` {String | Null} default = `null` - * `flag` {String} default = `'r'` -* `callback` {Function} - -Asynchronously reads the entire contents of a file. Example: - - fs.readFile('/etc/passwd', function (err, data) { - if (err) throw err; - console.log(data); - }); - -The callback is passed two arguments `(err, data)`, where `data` is the -contents of the file. - -If no encoding is specified, then the raw buffer is returned. - -If `options` is a string, then it specifies the encoding. Example: - - fs.readFile('/etc/passwd', 'utf8', callback); - -Any specified file descriptor has to support reading. - -_Note: Specified file descriptors will not be closed automatically._ - -## fs.readFileSync(file[, options]) - -Synchronous version of `fs.readFile`. Returns the contents of the `file`. - -If the `encoding` option is specified then this function returns a -string. Otherwise it returns a buffer. - -## fs.writeFile(file, data[, options], callback) +## fs.readlinkSync(path) -* `file` {String | Integer} filename or file descriptor -* `data` {String | Buffer} -* `options` {Object | String} - * `encoding` {String | Null} default = `'utf8'` - * `mode` {Number} default = `0o666` - * `flag` {String} default = `'w'` -* `callback` {Function} +Synchronous readlink(2). Returns the symbolic link's string value. -Asynchronously writes data to a file, replacing the file if it already exists. -`data` can be a string or a buffer. +## fs.realpath(path[, cache], callback) -The `encoding` option is ignored if `data` is a buffer. It defaults -to `'utf8'`. +Asynchronous realpath(2). The `callback` gets two arguments `(err, +resolvedPath)`. May use `process.cwd` to resolve relative paths. `cache` is an +object literal of mapped paths that can be used to force a specific path +resolution or avoid additional `fs.stat` calls for known real paths. Example: - fs.writeFile('message.txt', 'Hello Node.js', function (err) { + var cache = {'/etc':'/private/etc'}; + fs.realpath('/etc/passwd', cache, function (err, resolvedPath) { if (err) throw err; - console.log('It\'s saved!'); + console.log(resolvedPath); }); -If `options` is a string, then it specifies the encoding. Example: - - fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback); +## fs.realpathSync(path[, cache]) -Any specified file descriptor has to support writing. +Synchronous realpath(2). Returns the resolved path. -Note that it is unsafe to use `fs.writeFile` multiple times on the same file -without waiting for the callback. For this scenario, -`fs.createWriteStream` is strongly recommended. +## fs.rename(oldPath, newPath, callback) -_Note: Specified file descriptors will not be closed automatically._ +Asynchronous rename(2). No arguments other than a possible exception are given +to the completion callback. -## fs.writeFileSync(file, data[, options]) +## fs.renameSync(oldPath, newPath) -The synchronous version of `fs.writeFile`. Returns `undefined`. +Synchronous rename(2). Returns `undefined`. -## fs.appendFile(file, data[, options], callback) +## fs.rmdir(path, callback) -* `file` {String | Integer} filename or file descriptor -* `data` {String | Buffer} -* `options` {Object | String} - * `encoding` {String | Null} default = `'utf8'` - * `mode` {Number} default = `0o666` - * `flag` {String} default = `'a'` -* `callback` {Function} +Asynchronous rmdir(2). No arguments other than a possible exception are given +to the completion callback. -Asynchronously append data to a file, creating the file if it does not yet exist. -`data` can be a string or a buffer. +## fs.rmdirSync(path) -Example: +Synchronous rmdir(2). Returns `undefined`. - fs.appendFile('message.txt', 'data to append', function (err) { - if (err) throw err; - console.log('The "data to append" was appended to file!'); - }); +## fs.stat(path, callback) -If `options` is a string, then it specifies the encoding. Example: +Asynchronous stat(2). The callback gets two arguments `(err, stats)` where +`stats` is a [fs.Stats](#fs_class_fs_stats) object. See the [fs.Stats](#fs_class_fs_stats) +section below for more information. - fs.appendFile('message.txt', 'data to append', 'utf8', callback); +## fs.statSync(path) -Any specified file descriptor has to have been opened for appending. +Synchronous stat(2). Returns an instance of `fs.Stats`. -_Note: Specified file descriptors will not be closed automatically._ +## fs.symlink(destination, path[, type], callback) -## fs.appendFileSync(file, data[, options]) +Asynchronous symlink(2). No arguments other than a possible exception are given +to the completion callback. +The `type` argument can be set to `'dir'`, `'file'`, or `'junction'` (default +is `'file'`) and is only available on Windows (ignored on other platforms). +Note that Windows junction points require the destination path to be absolute. When using +`'junction'`, the `destination` argument will automatically be normalized to absolute path. -The synchronous version of `fs.appendFile`. Returns `undefined`. +## fs.symlinkSync(destination, path[, type]) -## fs.watchFile(filename[, options], listener) +Synchronous symlink(2). Returns `undefined`. -Watch for changes on `filename`. The callback `listener` will be called each -time the file is accessed. +## fs.truncate(path, len, callback) -The `options` argument may be omitted. If provided, it should be an object. The -`options` object may contain a boolean named `persistent` that indicates -whether the process should continue to run as long as files are being watched. -The `options` object may specify an `interval` property indicating how often the -target should be polled in milliseconds. The default is -`{ persistent: true, interval: 5007 }`. +Asynchronous truncate(2). No arguments other than a possible exception are +given to the completion callback. A file descriptor can also be passed as the +first argument. In this case, `fs.ftruncate()` is called. -The `listener` gets two arguments the current stat object and the previous -stat object: +## fs.truncateSync(path, len) - fs.watchFile('message.text', function (curr, prev) { - console.log('the current mtime is: ' + curr.mtime); - console.log('the previous mtime was: ' + prev.mtime); - }); +Synchronous truncate(2). Returns `undefined`. -These stat objects are instances of `fs.Stat`. +## fs.unlink(path, callback) -If you want to be notified when the file was modified, not just accessed, -you need to compare `curr.mtime` and `prev.mtime`. +Asynchronous unlink(2). No arguments other than a possible exception are given +to the completion callback. -_Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will - invoke the listener once, with all the fields zeroed (or, for dates, the Unix - Epoch). In Windows, `blksize` and `blocks` fields will be `undefined`, instead - 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._ +## fs.unlinkSync(path) -_Note: `fs.watch` is more efficient than `fs.watchFile` and `fs.unwatchFile`. -`fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` -when possible._ +Synchronous unlink(2). Returns `undefined`. ## fs.unwatchFile(filename[, listener]) @@ -622,6 +704,22 @@ _Note: `fs.watch` is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible._ +## fs.utimes(path, atime, mtime, callback) + +Change file timestamps of the file referenced by the supplied path. + +Note: the arguments `atime` and `mtime` of the following related functions does +follow the below rules: + +- If the value is a numberable string like "123456789", the value would get + converted to corresponding number. +- If the value is `NaN` or `Infinity`, the value would get converted to + `Date.now()`. + +## fs.utimesSync(path, atime, mtime) + +Synchronous version of `fs.utimes()`. Returns `undefined`. + ## fs.watch(filename[, options][, listener]) Watch for changes on `filename`, where `filename` is either a file or a @@ -688,239 +786,137 @@ provided in the callback, and have some fallback logic if it is null. } }); -## fs.exists(path, callback) - - Stability: 0 - Deprecated: Use [fs.stat][] or [fs.access][] instead. - -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: - - fs.exists('/etc/passwd', function (exists) { - console.log(exists ? "it's there" : 'no passwd!'); - }); - -`fs.exists()` should not be used to check if a file exists before calling -`fs.open()`. Doing so introduces a race condition since other processes may -change the file's state between the two calls. Instead, user code should -call `fs.open()` directly and handle the error raised if the file is -non-existent. - -## fs.existsSync(path) - -Synchronous version of [`fs.exists`](fs.html#fs_fs_exists_path_callback). -Returns `true` if the file exists, `false` otherwise. - - Stability: 0 - Deprecated: Use [fs.statSync][] or [fs.accessSync][] instead. - -## fs.access(path[, mode], callback) +## fs.watchFile(filename[, options], listener) -Tests a user's permissions for the file specified by `path`. `mode` is an -optional integer that specifies the accessibility checks to be performed. The -following constants define the possible values of `mode`. It is possible to -create a mask consisting of the bitwise OR of two or more values. +Watch for changes on `filename`. The callback `listener` will be called each +time the file is accessed. -- `fs.F_OK` - File is visible to the calling process. This is useful for -determining if a file exists, but says nothing about `rwx` permissions. -Default if no `mode` is specified. -- `fs.R_OK` - File can be read by the calling process. -- `fs.W_OK` - File can be written by the calling process. -- `fs.X_OK` - File can be executed by the calling process. This has no effect -on Windows (will behave like `fs.F_OK`). +The `options` argument may be omitted. If provided, it should be an object. The +`options` object may contain a boolean named `persistent` that indicates +whether the process should continue to run as long as files are being watched. +The `options` object may specify an `interval` property indicating how often the +target should be polled in milliseconds. The default is +`{ persistent: true, interval: 5007 }`. -The final argument, `callback`, is a callback function that is invoked with -a possible error argument. If any of the accessibility checks fail, the error -argument will be populated. The following example checks if the file -`/etc/passwd` can be read and written by the current process. +The `listener` gets two arguments the current stat object and the previous +stat object: - fs.access('/etc/passwd', fs.R_OK | fs.W_OK, function (err) { - console.log(err ? 'no access!' : 'can read/write'); + fs.watchFile('message.text', function (curr, prev) { + console.log('the current mtime is: ' + curr.mtime); + console.log('the previous mtime was: ' + prev.mtime); }); -## fs.accessSync(path[, mode]) - -Synchronous version of `fs.access`. This throws if any accessibility checks -fail, and does nothing otherwise. - -## Class: fs.Stats - -Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their -synchronous counterparts are of this type. - - - `stats.isFile()` - - `stats.isDirectory()` - - `stats.isBlockDevice()` - - `stats.isCharacterDevice()` - - `stats.isSymbolicLink()` (only valid with `fs.lstat()`) - - `stats.isFIFO()` - - `stats.isSocket()` - -For a regular file `util.inspect(stats)` would return a string very -similar to this: - - { dev: 2114, - ino: 48064969, - mode: 33188, - nlink: 1, - uid: 85, - gid: 100, - rdev: 0, - size: 527, - blksize: 4096, - blocks: 8, - atime: Mon, 10 Oct 2011 23:24:11 GMT, - mtime: Mon, 10 Oct 2011 23:24:11 GMT, - ctime: 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 -instances of [Date][MDN-Date] object and to compare the values of -these objects you should use appropriate methods. For most general -uses [getTime()][MDN-Date-getTime] will return the number of -milliseconds elapsed since _1 January 1970 00:00:00 UTC_ and this -integer should be sufficient for any comparison, however there are -additional methods which can be used for displaying fuzzy information. -More details can be found in the [MDN JavaScript Reference][MDN-Date] -page. - -[MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date -[MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime - -### Stat Time Values - -The times in the stat object have the following semantics: - -* `atime` "Access Time" - Time when file data last accessed. Changed - by the `mknod(2)`, `utimes(2)`, and `read(2)` system calls. -* `mtime` "Modified Time" - Time when file data last modified. - Changed by the `mknod(2)`, `utimes(2)`, and `write(2)` system calls. -* `ctime` "Change Time" - Time when file status was last changed - (inode data modification). Changed by the `chmod(2)`, `chown(2)`, - `link(2)`, `mknod(2)`, `rename(2)`, `unlink(2)`, `utimes(2)`, - `read(2)`, and `write(2)` system calls. -* `birthtime` "Birth Time" - Time of file creation. Set once when the - file is created. On filesystems where birthtime is not available, - this field may instead hold either the `ctime` or - `1970-01-01T00:00Z` (ie, unix epoch timestamp `0`). On Darwin and - other FreeBSD variants, also set if the `atime` is explicitly set to - an earlier value than the current `birthtime` using the `utimes(2)` - system call. - -Prior to Node v0.12, the `ctime` held the `birthtime` on Windows -systems. Note that as of v0.12, `ctime` is not "creation time", and -on Unix systems, it never was. - -## fs.createReadStream(path[, options]) - -Returns a new ReadStream object (See `Readable Stream`). - -Be aware that, unlike the default value set for `highWaterMark` on a -readable stream (16 kb), the stream returned by this method has a -default value of 64 kb for the same parameter. - -`options` is an object or string with the following defaults: - - { flags: 'r', - encoding: null, - fd: null, - mode: 0o666, - autoClose: true - } - -`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 -start at 0. The `encoding` can be `'utf8'`, `'ascii'`, or `'base64'`. - -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. - -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 no file descriptor leak. If `autoClose` is set to true (default -behavior), on `error` or `end` the file descriptor will be closed -automatically. - -`mode` sets the file mode (permission and sticky bits), but only if the -file was created. +These stat objects are instances of `fs.Stat`. -An example to read the last 10 bytes of a file which is 100 bytes long: +If you want to be notified when the file was modified, not just accessed, +you need to compare `curr.mtime` and `prev.mtime`. - fs.createReadStream('sample.txt', {start: 90, end: 99}); +_Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will + invoke the listener once, with all the fields zeroed (or, for dates, the Unix + Epoch). In Windows, `blksize` and `blocks` fields will be `undefined`, instead + 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._ -If `options` is a string, then it specifies the encoding. +_Note: `fs.watch` is more efficient than `fs.watchFile` and `fs.unwatchFile`. +`fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` +when possible._ -## Class: fs.ReadStream +## fs.write(fd, buffer, offset, length[, position], callback) -`ReadStream` is a [Readable Stream](stream.html#stream_class_stream_readable). +Write `buffer` to the file specified by `fd`. -### Event: 'open' +`offset` and `length` determine the part of the buffer to be written. -* `fd` {Integer} file descriptor used by the ReadStream. +`position` refers to the offset from the beginning of the file where this data +should be written. If `typeof position !== 'number'`, the data will be written +at the current position. See pwrite(2). -Emitted when the ReadStream's file is opened. +The callback will be given three arguments `(err, written, buffer)` where +`written` specifies how many _bytes_ were written from `buffer`. +Note that it is unsafe to use `fs.write` multiple times on the same file +without waiting for the callback. For this scenario, +`fs.createWriteStream` is strongly recommended. -## fs.createWriteStream(path[, options]) +On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file. -Returns a new WriteStream object (See `Writable Stream`). +## fs.write(fd, data[, position[, encoding]], callback) -`options` is an object or string with the following defaults: +Write `data` to the file specified by `fd`. If `data` is not a Buffer instance +then the value will be coerced to a string. - { flags: 'w', - defaultEncoding: 'utf8', - fd: null, - mode: 0o666 } +`position` refers to the offset from the beginning of the file where this data +should be written. If `typeof position !== 'number'` the data will be written at +the current position. See pwrite(2). -`options` may also include a `start` option to allow writing data at -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 -default mode `w`. The `defaultEncoding` can be `'utf8'`, `'ascii'`, `binary`, -or `'base64'`. +`encoding` is the expected string encoding. -Like `ReadStream` above, if `fd` is specified, `WriteStream` will ignore the -`path` argument and will use the specified file descriptor. This means that no -`open` event will be emitted. +The callback will receive the arguments `(err, written, string)` where `written` +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](buffer.html#buffer_class_method_buffer_bytelength_string_encoding). -If `options` is a string, then it specifies the encoding. +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 +be the same as the string offset. -## Class: fs.WriteStream +Note that it is unsafe to use `fs.write` multiple times on the same file +without waiting for the callback. For this scenario, +`fs.createWriteStream` is strongly recommended. -`WriteStream` is a [Writable Stream](stream.html#stream_class_stream_writable). +On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file. -### Event: 'open' +## fs.writeFile(file, data[, options], callback) -* `fd` {Integer} file descriptor used by the WriteStream. +* `file` {String | Integer} filename or file descriptor +* `data` {String | Buffer} +* `options` {Object | String} + * `encoding` {String | Null} default = `'utf8'` + * `mode` {Number} default = `0o666` + * `flag` {String} default = `'w'` +* `callback` {Function} -Emitted when the WriteStream's file is opened. +Asynchronously writes data to a file, replacing the file if it already exists. +`data` can be a string or a buffer. -### file.bytesWritten +The `encoding` option is ignored if `data` is a buffer. It defaults +to `'utf8'`. -The number of bytes written so far. Does not include data that is still queued -for writing. +Example: -## Class: fs.FSWatcher + fs.writeFile('message.txt', 'Hello Node.js', function (err) { + if (err) throw err; + console.log('It\'s saved!'); + }); -Objects returned from `fs.watch()` are of this type. +If `options` is a string, then it specifies the encoding. Example: -### watcher.close() + fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback); -Stop watching for changes on the given `fs.FSWatcher`. +Any specified file descriptor has to support writing. -### Event: 'change' +Note that it is unsafe to use `fs.writeFile` multiple times on the same file +without waiting for the callback. For this scenario, +`fs.createWriteStream` is strongly recommended. -* `event` {String} The type of fs change -* `filename` {String} The filename that changed (if relevant/available) +_Note: Specified file descriptors will not be closed automatically._ -Emitted when something changes in a watched directory or file. -See more details in [fs.watch](#fs_fs_watch_filename_options_listener). +## fs.writeFileSync(file, data[, options]) -### Event: 'error' +The synchronous version of `fs.writeFile`. Returns `undefined`. -* `error` {Error object} +## fs.writeSync(fd, buffer, offset, length[, position]) -Emitted when an error occurs. +## fs.writeSync(fd, data[, position[, encoding]]) +Synchronous versions of `fs.write()`. Returns the number of bytes written. [fs.stat]: #fs_fs_stat_path_callback [fs.access]: #fs_fs_access_path_mode_callback [fs.statSync]: #fs_fs_statsync_path [fs.accessSync]: #fs_fs_accesssync_path_mode +[Buffer]: buffer.html#buffer_buffer From 0c181d129ea75feb52f7ee6a306a6d7fffb427fa Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:12:06 -0500 Subject: [PATCH 12/32] doc: sort globals alphabetically Reorders, with no contextual changes, the globals documentation alphabetically. --- doc/api/globals.markdown | 193 +++++++++++++++++++-------------------- 1 file changed, 96 insertions(+), 97 deletions(-) diff --git a/doc/api/globals.markdown b/doc/api/globals.markdown index 2a2140fe532452..b9ab51ad8da066 100644 --- a/doc/api/globals.markdown +++ b/doc/api/globals.markdown @@ -5,33 +5,6 @@ These objects are available in all modules. Some of these objects aren't actually in the global scope but in the module scope - this will be noted. -## global - - - -* {Object} The global namespace object. - -In browsers, the top-level scope is the global scope. That means that in -browsers if you're in the global scope `var something` will define a global -variable. In Node.js this is different. The top-level scope is not the global -scope; `var something` inside an Node.js module will be local to that module. - -## process - - - -* {Object} - -The process object. See the [process object][] section. - -## console - - - -* {Object} - -Used to print to stdout and stderr. See the [console][] section. - ## Class: Buffer @@ -40,48 +13,20 @@ Used to print to stdout and stderr. See the [console][] section. Used to handle binary data. See the [buffer section][] -## require() +## __dirname -* {Function} - -To require modules. See the [Modules][] section. `require` isn't actually a -global but rather local to each module. - -### require.resolve() - -Use the internal `require()` machinery to look up the location of a module, -but rather than loading the module, just return the resolved filename. - -### require.cache - -* {Object} - -Modules are cached in this object when they are required. By deleting a key -value from this object, the next `require` will reload the module. - -### require.extensions - - Stability: 0 - Deprecated - -* {Object} - -Instruct `require` on how to handle certain file extensions. +* {String} -Process files with the extension `.sjs` as `.js`: +The name of the directory that the currently executing script resides in. - require.extensions['.sjs'] = require.extensions['.js']; +Example: running `node example.js` from `/Users/mjr` -**Deprecated** In the past, this list has been used to load -non-JavaScript modules into Node.js by compiling them on-demand. -However, in practice, there are much better ways to do this, such as -loading modules via some other Node.js program, or compiling them to -JavaScript ahead of time. + console.log(__dirname); + // /Users/mjr -Since the Module system is locked, this feature will probably never go -away. However, it may have subtle bugs and complexities that are best -left untouched. +`__dirname` isn't actually a global but rather local to each module. ## __filename @@ -101,21 +46,57 @@ Example: running `node example.js` from `/Users/mjr` `__filename` isn't actually a global but rather local to each module. -## __dirname +## clearInterval(t) + +Stop a timer that was previously created with `setInterval()`. The callback +will not execute. + + + +The timer functions are global variables. See the [timers][] section. + +[buffer section]: buffer.html +[module system documentation]: modules.html +[Modules]: modules.html#modules_modules +[process object]: process.html#process_process +[console]: console.html +[timers]: timers.html + +## clearTimeout(t) + +Stop a timer that was previously created with `setTimeout()`. The callback will +not execute. + +## console + + + +* {Object} + +Used to print to stdout and stderr. See the [console][] section. + +## exports -* {String} +A reference to the `module.exports` that is shorter to type. +See [module system documentation][] for details on when to use `exports` and +when to use `module.exports`. -The name of the directory that the currently executing script resides in. +`exports` isn't actually a global but rather local to each module. -Example: running `node example.js` from `/Users/mjr` +See the [module system documentation][] for more information. - console.log(__dirname); - // /Users/mjr +## global -`__dirname` isn't actually a global but rather local to each module. + + +* {Object} The global namespace object. +In browsers, the top-level scope is the global scope. That means that in +browsers if you're in the global scope `var something` will define a global +variable. In Node.js this is different. The top-level scope is not the global +scope; `var something` inside an Node.js module will be local to that module. ## module @@ -131,33 +112,56 @@ available through `require()`. See the [module system documentation][] for more information. -## exports +## process + + + +* {Object} + +The process object. See the [process object][] section. + +## require() -A reference to the `module.exports` that is shorter to type. -See [module system documentation][] for details on when to use `exports` and -when to use `module.exports`. +* {Function} -`exports` isn't actually a global but rather local to each module. +To require modules. See the [Modules][] section. `require` isn't actually a +global but rather local to each module. -See the [module system documentation][] for more information. +### require.cache -## setTimeout(cb, ms) +* {Object} -Run callback `cb` after *at least* `ms` milliseconds. The actual delay depends -on external factors like OS timer granularity and system load. +Modules are cached in this object when they are required. By deleting a key +value from this object, the next `require` will reload the module. -The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is -outside that range, it's changed to 1 millisecond. Broadly speaking, a timer -cannot span more than 24.8 days. +### require.extensions -Returns an opaque value that represents the timer. + Stability: 0 - Deprecated -## clearTimeout(t) +* {Object} -Stop a timer that was previously created with `setTimeout()`. The callback will -not execute. +Instruct `require` on how to handle certain file extensions. + +Process files with the extension `.sjs` as `.js`: + + require.extensions['.sjs'] = require.extensions['.js']; + +**Deprecated** In the past, this list has been used to load +non-JavaScript modules into Node.js by compiling them on-demand. +However, in practice, there are much better ways to do this, such as +loading modules via some other Node.js program, or compiling them to +JavaScript ahead of time. + +Since the Module system is locked, this feature will probably never go +away. However, it may have subtle bugs and complexities that are best +left untouched. + +### require.resolve() + +Use the internal `require()` machinery to look up the location of a module, +but rather than loading the module, just return the resolved filename. ## setInterval(cb, ms) @@ -171,18 +175,13 @@ cannot span more than 24.8 days. Returns an opaque value that represents the timer. -## clearInterval(t) - -Stop a timer that was previously created with `setInterval()`. The callback -will not execute. +## setTimeout(cb, ms) - +Run callback `cb` after *at least* `ms` milliseconds. The actual delay depends +on external factors like OS timer granularity and system load. -The timer functions are global variables. See the [timers][] section. +The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is +outside that range, it's changed to 1 millisecond. Broadly speaking, a timer +cannot span more than 24.8 days. -[buffer section]: buffer.html -[module system documentation]: modules.html -[Modules]: modules.html#modules_modules -[process object]: process.html#process_process -[console]: console.html -[timers]: timers.html +Returns an opaque value that represents the timer. From 99c8160f37f7557c1216fd7f327ed4eb8f76796b Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:19:49 -0500 Subject: [PATCH 13/32] doc: sort os alphabetically Reorders, with no contextual changes, the os documentation alphabetically. --- doc/api/os.markdown | 114 ++++++++++++++++++++++---------------------- 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/doc/api/os.markdown b/doc/api/os.markdown index 4a7bf6633ec297..bef2c34f6a4915 100644 --- a/doc/api/os.markdown +++ b/doc/api/os.markdown @@ -6,67 +6,16 @@ Provides a few basic operating-system related utility functions. Use `require('os')` to access this module. -## os.tmpdir() - -Returns the operating system's default directory for temporary files. - -## os.homedir() - -Returns the home directory of the current user. - -## os.endianness() - -Returns the endianness of the CPU. Possible values are `'BE'` for big endian -or `'LE'` for little endian. - -## os.hostname() - -Returns the hostname of the operating system. - -## os.type() - -Returns the operating system name. For example `'Linux'` on Linux, `'Darwin'` -on OS X and `'Windows_NT'` on Windows. - -## os.platform() +## os.EOL -Returns the operating system platform. Possible values are `'darwin'`, -`'freebsd'`, `'linux'`, `'sunos'` or `'win32'`. Returns the value of -`process.platform`. +A constant defining the appropriate End-of-line marker for the operating +system. ## os.arch() Returns the operating system CPU architecture. Possible values are `'x64'`, `'arm'` and `'ia32'`. Returns the value of `process.arch`. -## os.release() - -Returns the operating system release. - -## os.uptime() - -Returns the system uptime in seconds. - -## os.loadavg() - -Returns an array containing the 1, 5, and 15 minute load averages. - -The load average is a measure of system activity, calculated by the operating -system and expressed as a fractional number. As a rule of thumb, the load -average should ideally be less than the number of logical CPUs in the system. - -The load average is a very UNIX-y concept; there is no real equivalent on -Windows platforms. That is why this function always returns `[0, 0, 0]` on -Windows. - -## os.totalmem() - -Returns the total amount of system memory in bytes. - -## os.freemem() - -Returns the amount of free system memory in bytes. - ## os.cpus() Returns an array of objects containing information about each CPU/core @@ -143,6 +92,35 @@ Example inspection of os.cpus: Note that since `nice` values are UNIX centric in Windows the `nice` values of all processors are always 0. +## os.endianness() + +Returns the endianness of the CPU. Possible values are `'BE'` for big endian +or `'LE'` for little endian. + +## os.freemem() + +Returns the amount of free system memory in bytes. + +## os.homedir() + +Returns the home directory of the current user. + +## os.hostname() + +Returns the hostname of the operating system. + +## os.loadavg() + +Returns an array containing the 1, 5, and 15 minute load averages. + +The load average is a measure of system activity, calculated by the operating +system and expressed as a fractional number. As a rule of thumb, the load +average should ideally be less than the number of logical CPUs in the system. + +The load average is a very UNIX-y concept; there is no real equivalent on +Windows platforms. That is why this function always returns `[0, 0, 0]` on +Windows. + ## os.networkInterfaces() Get a list of network interfaces: @@ -173,7 +151,29 @@ Get a list of network interfaces: Note that due to the underlying implementation this will only return network interfaces that have been assigned an address. -## os.EOL +## os.platform() -A constant defining the appropriate End-of-line marker for the operating -system. +Returns the operating system platform. Possible values are `'darwin'`, +`'freebsd'`, `'linux'`, `'sunos'` or `'win32'`. Returns the value of +`process.platform`. + +## os.release() + +Returns the operating system release. + +## os.tmpdir() + +Returns the operating system's default directory for temporary files. + +## os.totalmem() + +Returns the total amount of system memory in bytes. + +## os.type() + +Returns the operating system name. For example `'Linux'` on Linux, `'Darwin'` +on OS X and `'Windows_NT'` on Windows. + +## os.uptime() + +Returns the system uptime in seconds. From 820506e4a51a99f2b7483df4644167b647c846e9 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:23:52 -0500 Subject: [PATCH 14/32] doc: sort path alphabetically Reorders, with no contextual changes, the path documentation alphabetically. --- doc/api/path.markdown | 310 +++++++++++++++++++++--------------------- 1 file changed, 155 insertions(+), 155 deletions(-) diff --git a/doc/api/path.markdown b/doc/api/path.markdown index 7a06ec68f2df1d..454c79353f7b3c 100644 --- a/doc/api/path.markdown +++ b/doc/api/path.markdown @@ -8,86 +8,92 @@ The file system is not consulted to check whether paths are valid. Use `require('path')` to use this module. The following methods are provided: -## path.normalize(p) - -Normalize a string path, taking care of `'..'` and `'.'` parts. +## path.basename(p[, ext]) -When multiple slashes are found, they're replaced by a single one; -when the path contains a trailing slash, it is preserved. -On Windows backslashes are used. +Return the last portion of a path. Similar to the Unix `basename` command. Example: - path.normalize('/foo/bar//baz/asdf/quux/..') + path.basename('/foo/bar/baz/asdf/quux.html') // returns - '/foo/bar/baz/asdf' + 'quux.html' -*Note:* If the path string passed as argument is a zero-length string then `'.'` - will be returned, which represents the current working directory. + path.basename('/foo/bar/baz/asdf/quux.html', '.html') + // returns + 'quux' -## path.join([path1][, path2][, ...]) +## path.delimiter -Join all arguments together and normalize the resulting path. +The platform-specific path delimiter, `;` or `':'`. -Arguments must be strings. In v0.8, non-string arguments were -silently ignored. In v0.10 and up, an exception is thrown. +An example on *nix: -Example: + console.log(process.env.PATH) + // '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' - path.join('/foo', 'bar', 'baz/asdf', 'quux', '..') + process.env.PATH.split(path.delimiter) // returns - '/foo/bar/baz/asdf' + ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] - path.join('foo', {}, 'bar') - // throws exception - TypeError: Arguments to path.join must be strings +An example on Windows: -*Note:* If the arguments to `join` have zero-length strings, unlike other path - module functions, they will be ignored. If the joined path string is a - zero-length string then `'.'` will be returned, which represents the - current working directory. + console.log(process.env.PATH) + // 'C:\Windows\system32;C:\Windows;C:\Program Files\node\' -## path.resolve([from ...], to) + process.env.PATH.split(path.delimiter) + // returns + ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\'] -Resolves `to` to an absolute path. +## path.dirname(p) -If `to` isn't already absolute `from` arguments are prepended in right to left -order, until an absolute path is found. If after using all `from` paths still -no absolute path is found, the current working directory is used as well. The -resulting path is normalized, and trailing slashes are removed unless the path -gets resolved to the root directory. Non-string `from` arguments are ignored. +Return the directory name of a path. Similar to the Unix `dirname` command. -Another way to think of it is as a sequence of `cd` commands in a shell. +Example: - path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile') + path.dirname('/foo/bar/baz/asdf/quux') + // returns + '/foo/bar/baz/asdf' -Is similar to: +## path.extname(p) - cd foo/bar - cd /tmp/file/ - cd .. - cd a/../subfile - pwd +Return the extension of the path, from the last '.' to end of string +in the last portion of the path. If there is no '.' in the last portion +of the path or the first character of it is '.', then it returns +an empty string. Examples: -The difference is that the different paths don't need to exist and may also be -files. + path.extname('index.html') + // returns + '.html' -Examples: + path.extname('index.coffee.md') + // returns + '.md' - path.resolve('/foo/bar', './baz') + path.extname('index.') // returns - '/foo/bar/baz' + '.' - path.resolve('/foo/bar', '/tmp/file/') + path.extname('index') // returns - '/tmp/file' + '' - path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif') - // if currently in /home/myself/node, it returns - '/home/myself/node/wwwroot/static_files/gif/image.gif' + path.extname('.index') + // returns + '' -*Note:* If the arguments to `resolve` have zero-length strings then the current - working directory will be used instead of them. +## path.format(pathObject) + +Returns a path string from an object, the opposite of `path.parse` above. + + path.format({ + root : "/", + dir : "/home/user/dir", + base : "file.txt", + ext : ".txt", + name : "file" + }) + // returns + '/home/user/dir/file.txt' ## path.isAbsolute(path) @@ -112,165 +118,159 @@ Windows examples: other path module functions, it will be used as-is and `false` will be returned. -## path.relative(from, to) - -Solve the relative path from `from` to `to`. +## path.join([path1][, path2][, ...]) -At times we have two absolute paths, and we need to derive the relative -path from one to the other. This is actually the reverse transform of -`path.resolve`, which means we see that: +Join all arguments together and normalize the resulting path. - path.resolve(from, path.relative(from, to)) == path.resolve(to) +Arguments must be strings. In v0.8, non-string arguments were +silently ignored. In v0.10 and up, an exception is thrown. -Examples: +Example: - path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb') + path.join('/foo', 'bar', 'baz/asdf', 'quux', '..') // returns - '..\\..\\impl\\bbb' + '/foo/bar/baz/asdf' - path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') - // returns - '../../impl/bbb' + path.join('foo', {}, 'bar') + // throws exception + TypeError: Arguments to path.join must be strings -*Note:* If the arguments to `relative` have zero-length strings then the current - working directory will be used instead of the zero-length strings. If - both the paths are the same then a zero-length string will be returned. +*Note:* If the arguments to `join` have zero-length strings, unlike other path + module functions, they will be ignored. If the joined path string is a + zero-length string then `'.'` will be returned, which represents the + current working directory. -## path.dirname(p) +## path.normalize(p) -Return the directory name of a path. Similar to the Unix `dirname` command. +Normalize a string path, taking care of `'..'` and `'.'` parts. + +When multiple slashes are found, they're replaced by a single one; +when the path contains a trailing slash, it is preserved. +On Windows backslashes are used. Example: - path.dirname('/foo/bar/baz/asdf/quux') + path.normalize('/foo/bar//baz/asdf/quux/..') // returns '/foo/bar/baz/asdf' -## path.basename(p[, ext]) +*Note:* If the path string passed as argument is a zero-length string then `'.'` + will be returned, which represents the current working directory. -Return the last portion of a path. Similar to the Unix `basename` command. +## path.parse(pathString) -Example: +Returns an object from a path string. - path.basename('/foo/bar/baz/asdf/quux.html') - // returns - 'quux.html' +An example on *nix: - path.basename('/foo/bar/baz/asdf/quux.html', '.html') + path.parse('/home/user/dir/file.txt') // returns - 'quux' - -## path.extname(p) + { + root : "/", + dir : "/home/user/dir", + base : "file.txt", + ext : ".txt", + name : "file" + } -Return the extension of the path, from the last '.' to end of string -in the last portion of the path. If there is no '.' in the last portion -of the path or the first character of it is '.', then it returns -an empty string. Examples: +An example on Windows: - path.extname('index.html') + path.parse('C:\\path\\dir\\index.html') // returns - '.html' + { + root : "C:\\", + dir : "C:\\path\\dir", + base : "index.html", + ext : ".html", + name : "index" + } - path.extname('index.coffee.md') - // returns - '.md' +## path.posix - path.extname('index.') - // returns - '.' +Provide access to aforementioned `path` methods but always interact in a posix +compatible way. - path.extname('index') - // returns - '' +## path.relative(from, to) - path.extname('.index') - // returns - '' +Solve the relative path from `from` to `to`. -## path.sep +At times we have two absolute paths, and we need to derive the relative +path from one to the other. This is actually the reverse transform of +`path.resolve`, which means we see that: -The platform-specific file separator. `'\\'` or `'/'`. + path.resolve(from, path.relative(from, to)) == path.resolve(to) -An example on *nix: +Examples: - 'foo/bar/baz'.split(path.sep) + path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb') // returns - ['foo', 'bar', 'baz'] - -An example on Windows: + '..\\..\\impl\\bbb' - 'foo\\bar\\baz'.split(path.sep) + path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') // returns - ['foo', 'bar', 'baz'] + '../../impl/bbb' -## path.delimiter +*Note:* If the arguments to `relative` have zero-length strings then the current + working directory will be used instead of the zero-length strings. If + both the paths are the same then a zero-length string will be returned. -The platform-specific path delimiter, `;` or `':'`. +## path.resolve([from ...], to) -An example on *nix: +Resolves `to` to an absolute path. - console.log(process.env.PATH) - // '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' +If `to` isn't already absolute `from` arguments are prepended in right to left +order, until an absolute path is found. If after using all `from` paths still +no absolute path is found, the current working directory is used as well. The +resulting path is normalized, and trailing slashes are removed unless the path +gets resolved to the root directory. Non-string `from` arguments are ignored. - process.env.PATH.split(path.delimiter) - // returns - ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] +Another way to think of it is as a sequence of `cd` commands in a shell. -An example on Windows: + path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile') - console.log(process.env.PATH) - // 'C:\Windows\system32;C:\Windows;C:\Program Files\node\' +Is similar to: - process.env.PATH.split(path.delimiter) - // returns - ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\'] + cd foo/bar + cd /tmp/file/ + cd .. + cd a/../subfile + pwd -## path.parse(pathString) +The difference is that the different paths don't need to exist and may also be +files. -Returns an object from a path string. +Examples: -An example on *nix: + path.resolve('/foo/bar', './baz') + // returns + '/foo/bar/baz' - path.parse('/home/user/dir/file.txt') + path.resolve('/foo/bar', '/tmp/file/') // returns - { - root : "/", - dir : "/home/user/dir", - base : "file.txt", - ext : ".txt", - name : "file" - } + '/tmp/file' -An example on Windows: + path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif') + // if currently in /home/myself/node, it returns + '/home/myself/node/wwwroot/static_files/gif/image.gif' - path.parse('C:\\path\\dir\\index.html') - // returns - { - root : "C:\\", - dir : "C:\\path\\dir", - base : "index.html", - ext : ".html", - name : "index" - } +*Note:* If the arguments to `resolve` have zero-length strings then the current + working directory will be used instead of them. -## path.format(pathObject) +## path.sep -Returns a path string from an object, the opposite of `path.parse` above. +The platform-specific file separator. `'\\'` or `'/'`. - path.format({ - root : "/", - dir : "/home/user/dir", - base : "file.txt", - ext : ".txt", - name : "file" - }) +An example on *nix: + + 'foo/bar/baz'.split(path.sep) // returns - '/home/user/dir/file.txt' + ['foo', 'bar', 'baz'] -## path.posix +An example on Windows: -Provide access to aforementioned `path` methods but always interact in a posix -compatible way. + 'foo\\bar\\baz'.split(path.sep) + // returns + ['foo', 'bar', 'baz'] ## path.win32 From 33a697595287dd10aa066bda2e5ad5836207b7a1 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:25:20 -0500 Subject: [PATCH 15/32] doc: sort punycode alphabetically Reorders, with no contextual changes, the punycode documentation alphabetically. --- doc/api/punycode.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/doc/api/punycode.markdown b/doc/api/punycode.markdown index fe29bdd4b06d11..f86b32ba50db66 100644 --- a/doc/api/punycode.markdown +++ b/doc/api/punycode.markdown @@ -22,16 +22,6 @@ Converts a string of Unicode symbols to a Punycode string of ASCII-only symbols. punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' -## punycode.toUnicode(domain) - -Converts a Punycode string representing a domain name to Unicode. Only the -Punycoded parts of the domain name will be converted, i.e. it doesn't matter if -you call it on a string that has already been converted to Unicode. - - // decode domain names - punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' - punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' - ## punycode.toASCII(domain) Converts a Unicode string representing a domain name to Punycode. Only the @@ -42,6 +32,16 @@ you call it with a domain that's already in ASCII. punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' +## punycode.toUnicode(domain) + +Converts a Punycode string representing a domain name to Unicode. Only the +Punycoded parts of the domain name will be converted, i.e. it doesn't matter if +you call it on a string that has already been converted to Unicode. + + // decode domain names + punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + ## punycode.ucs2 ### punycode.ucs2.decode(string) From 5c374626489dac25dc8da42f78163be7c41a48e4 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:26:30 -0500 Subject: [PATCH 16/32] doc: sort querystring alphabetically Reorders, with no contextual changes, the querystring documentation alphabetically. --- doc/api/querystring.markdown | 54 ++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/doc/api/querystring.markdown b/doc/api/querystring.markdown index 37144974c548e5..8b16fb725aeef0 100644 --- a/doc/api/querystring.markdown +++ b/doc/api/querystring.markdown @@ -7,31 +7,10 @@ This module provides utilities for dealing with query strings. It provides the following methods: -## querystring.stringify(obj[, sep][, eq][, options]) - -Serialize an object to a query string. -Optionally override the default separator (`'&'`) and assignment (`'='`) -characters. - -Options object may contain `encodeURIComponent` property (`querystring.escape` by default), -it can be used to encode string with `non-utf8` encoding if necessary. - -Example: - - querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }) - // returns - 'foo=bar&baz=qux&baz=quux&corge=' - - querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':') - // returns - 'foo:bar;baz:qux' +## querystring.escape - // Suppose gbkEncodeURIComponent function already exists, - // it can encode string with `gbk` encoding - querystring.stringify({ w: '中文', foo: 'bar' }, null, null, - { encodeURIComponent: gbkEncodeURIComponent }) - // returns - 'w=%D6%D0%CE%C4&foo=bar' +The escape function used by `querystring.stringify`, +provided so that it could be overridden if necessary. ## querystring.parse(str[, sep][, eq][, options]) @@ -58,10 +37,31 @@ Example: // returns { w: '中文', foo: 'bar' } -## querystring.escape +## querystring.stringify(obj[, sep][, eq][, options]) -The escape function used by `querystring.stringify`, -provided so that it could be overridden if necessary. +Serialize an object to a query string. +Optionally override the default separator (`'&'`) and assignment (`'='`) +characters. + +Options object may contain `encodeURIComponent` property (`querystring.escape` by default), +it can be used to encode string with `non-utf8` encoding if necessary. + +Example: + + querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }) + // returns + 'foo=bar&baz=qux&baz=quux&corge=' + + querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':') + // returns + 'foo:bar;baz:qux' + + // Suppose gbkEncodeURIComponent function already exists, + // it can encode string with `gbk` encoding + querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + { encodeURIComponent: gbkEncodeURIComponent }) + // returns + 'w=%D6%D0%CE%C4&foo=bar' ## querystring.unescape From ac629413803b9fce59dad482695c9949cded652b Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:30:11 -0500 Subject: [PATCH 17/32] doc: sort vm alphabetically Reorders, with no contextual changes, the vm documentation alphabetically. --- doc/api/vm.markdown | 296 +++++++++++++++++++++----------------------- 1 file changed, 143 insertions(+), 153 deletions(-) diff --git a/doc/api/vm.markdown b/doc/api/vm.markdown index dd2593ecb7a7b2..20bca8770286ab 100644 --- a/doc/api/vm.markdown +++ b/doc/api/vm.markdown @@ -11,45 +11,125 @@ You can access this module with: JavaScript code can be compiled and run immediately or compiled, saved, and run later. -## vm.runInThisContext(code[, options]) +## Class: Script -`vm.runInThisContext()` compiles `code`, runs it and returns the result. Running -code does not have access to local scope, but does have access to the current -`global` object. +A class for holding precompiled scripts, and running them in specific sandboxes. -Example of using `vm.runInThisContext` and `eval` to run the same code: +### new vm.Script(code, options) +Creating a new `Script` compiles `code` but does not run it. Instead, the +created `vm.Script` object represents this compiled code. This script can be run +later many times using methods below. The returned script is not bound to any +global object. It is bound before each run, just for that run. + +The options when creating a script are: + +- `filename`: allows you to control the filename that shows up in any stack + traces produced from this script. +- `displayErrors`: whether or not to print any errors to stderr, with the + line of code that caused them highlighted, before throwing an exception. + Applies only to syntax errors compiling the code; errors while running the + code are controlled by the options to the script's methods. + +### script.runInContext(contextifiedSandbox[, options]) + +Similar to `vm.runInContext` but a method of a precompiled `Script` object. +`script.runInContext` runs `script`'s compiled code in `contextifiedSandbox` +and returns the result. Running code does not have access to local scope. + +`script.runInContext` takes the same options as `script.runInThisContext`. + +Example: compile code that increments a global variable and sets one, then +execute the code multiple times. These globals are contained in the sandbox. + + var util = require('util'); var vm = require('vm'); - var localVar = 'initial value'; - var vmResult = vm.runInThisContext('localVar = "vm";'); - console.log('vmResult: ', vmResult); - console.log('localVar: ', localVar); + var sandbox = { + animal: 'cat', + count: 2 + }; - var evalResult = eval('localVar = "eval";'); - console.log('evalResult: ', evalResult); - console.log('localVar: ', localVar); + var context = new vm.createContext(sandbox); + var script = new vm.Script('count += 1; name = "kitty"'); - // vmResult: 'vm', localVar: 'initial value' - // evalResult: 'eval', localVar: 'eval' + for (var i = 0; i < 10; ++i) { + script.runInContext(context); + } -`vm.runInThisContext` does not have access to the local scope, so `localVar` is -unchanged. `eval` does have access to the local scope, so `localVar` is changed. + console.log(util.inspect(sandbox)); -In this way `vm.runInThisContext` is much like an [indirect `eval` call][1], -e.g. `(0,eval)('code')`. However, it also has the following additional options: + // { animal: 'cat', count: 12, name: 'kitty' } -- `filename`: allows you to control the filename that shows up in any stack - traces produced. -- `displayErrors`: whether or not to print any errors to stderr, with the - line of code that caused them highlighted, before throwing an exception. - Will capture both syntax errors from compiling `code` and runtime errors - thrown by executing the compiled code. Defaults to `true`. -- `timeout`: a number of milliseconds to execute `code` before terminating - execution. If execution is terminated, an `Error` will be thrown. +Note that running untrusted code is a tricky business requiring great care. +`script.runInContext` is quite useful, but safely running untrusted code +requires a separate process. -[1]: http://es5.github.io/#x10.4.2 +### script.runInNewContext([sandbox][, options]) + +Similar to `vm.runInNewContext` but a method of a precompiled `Script` object. +`script.runInNewContext` contextifies `sandbox` if passed or creates a new +contextified sandbox if it's omitted, and then runs `script`'s compiled code +with the sandbox as the global object and returns the result. Running code does +not have access to local scope. + +`script.runInNewContext` takes the same options as `script.runInThisContext`. + +Example: compile code that sets a global variable, then execute the code +multiple times in different contexts. These globals are set on and contained in +the sandboxes. + + var util = require('util'); + var vm = require('vm'); + + var sandboxes = [{}, {}, {}]; + + var script = new vm.Script('globalVar = "set"'); + + sandboxes.forEach(function (sandbox) { + script.runInNewContext(sandbox); + }); + + console.log(util.inspect(sandboxes)); + + // [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] + +Note that running untrusted code is a tricky business requiring great care. +`script.runInNewContext` is quite useful, but safely running untrusted code +requires a separate process. + +### script.runInThisContext([options]) + +Similar to `vm.runInThisContext` but a method of a precompiled `Script` object. +`script.runInThisContext` runs `script`'s compiled code and returns the result. +Running code does not have access to local scope, but does have access to the +current `global` object. + +Example of using `script.runInThisContext` to compile code once and run it +multiple times: + + var vm = require('vm'); + + global.globalVar = 0; + var script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + + for (var i = 0; i < 1000; ++i) { + script.runInThisContext(); + } + + console.log(globalVar); + + // 1000 + +The options for running a script are: + +- `displayErrors`: whether or not to print any runtime errors to stderr, with + the line of code that caused them highlighted, before throwing an exception. + Applies only to runtime errors executing the code; it is impossible to create + a `Script` instance with syntax errors, as the constructor will throw. +- `timeout`: a number of milliseconds to execute the script before terminating + execution. If execution is terminated, an `Error` will be thrown. ## vm.createContext([sandbox]) @@ -70,13 +150,11 @@ tags together inside that sandbox. [2]: http://es5.github.io/#x15.1 - ## vm.isContext(sandbox) Returns whether or not a sandbox object has been contextified by calling `vm.createContext` on it. - ## vm.runInContext(code, contextifiedSandbox[, options]) `vm.runInContext` compiles `code`, then runs it in `contextifiedSandbox` and @@ -105,6 +183,18 @@ Note that running untrusted code is a tricky business requiring great care. `vm.runInContext` is quite useful, but safely running untrusted code requires a separate process. +## vm.runInDebugContext(code) + +`vm.runInDebugContext` compiles and executes `code` inside the V8 debug context. +The primary use case is to get access to the V8 debug object: + + var Debug = vm.runInDebugContext('Debug'); + Debug.scripts().forEach(function(script) { console.log(script.name); }); + +Note that the debug context and object are intrinsically tied to V8's debugger +implementation and may change (or even get removed) without prior warning. + +The debug object can also be exposed with the `--expose_debug_as=` switch. ## vm.runInNewContext(code[, sandbox][, options]) @@ -134,141 +224,41 @@ Note that running untrusted code is a tricky business requiring great care. `vm.runInNewContext` is quite useful, but safely running untrusted code requires a separate process. +## vm.runInThisContext(code[, options]) -## vm.runInDebugContext(code) - -`vm.runInDebugContext` compiles and executes `code` inside the V8 debug context. -The primary use case is to get access to the V8 debug object: - - var Debug = vm.runInDebugContext('Debug'); - Debug.scripts().forEach(function(script) { console.log(script.name); }); - -Note that the debug context and object are intrinsically tied to V8's debugger -implementation and may change (or even get removed) without prior warning. - -The debug object can also be exposed with the `--expose_debug_as=` switch. +`vm.runInThisContext()` compiles `code`, runs it and returns the result. Running +code does not have access to local scope, but does have access to the current +`global` object. +Example of using `vm.runInThisContext` and `eval` to run the same code: -## Class: Script + var vm = require('vm'); + var localVar = 'initial value'; -A class for holding precompiled scripts, and running them in specific sandboxes. + var vmResult = vm.runInThisContext('localVar = "vm";'); + console.log('vmResult: ', vmResult); + console.log('localVar: ', localVar); + var evalResult = eval('localVar = "eval";'); + console.log('evalResult: ', evalResult); + console.log('localVar: ', localVar); -### new vm.Script(code, options) + // vmResult: 'vm', localVar: 'initial value' + // evalResult: 'eval', localVar: 'eval' -Creating a new `Script` compiles `code` but does not run it. Instead, the -created `vm.Script` object represents this compiled code. This script can be run -later many times using methods below. The returned script is not bound to any -global object. It is bound before each run, just for that run. +`vm.runInThisContext` does not have access to the local scope, so `localVar` is +unchanged. `eval` does have access to the local scope, so `localVar` is changed. -The options when creating a script are: +In this way `vm.runInThisContext` is much like an [indirect `eval` call][1], +e.g. `(0,eval)('code')`. However, it also has the following additional options: - `filename`: allows you to control the filename that shows up in any stack - traces produced from this script. + traces produced. - `displayErrors`: whether or not to print any errors to stderr, with the line of code that caused them highlighted, before throwing an exception. - Applies only to syntax errors compiling the code; errors while running the - code are controlled by the options to the script's methods. - - -### script.runInThisContext([options]) - -Similar to `vm.runInThisContext` but a method of a precompiled `Script` object. -`script.runInThisContext` runs `script`'s compiled code and returns the result. -Running code does not have access to local scope, but does have access to the -current `global` object. - -Example of using `script.runInThisContext` to compile code once and run it -multiple times: - - var vm = require('vm'); - - global.globalVar = 0; - - var script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); - - for (var i = 0; i < 1000; ++i) { - script.runInThisContext(); - } - - console.log(globalVar); - - // 1000 - -The options for running a script are: - -- `displayErrors`: whether or not to print any runtime errors to stderr, with - the line of code that caused them highlighted, before throwing an exception. - Applies only to runtime errors executing the code; it is impossible to create - a `Script` instance with syntax errors, as the constructor will throw. -- `timeout`: a number of milliseconds to execute the script before terminating + Will capture both syntax errors from compiling `code` and runtime errors + thrown by executing the compiled code. Defaults to `true`. +- `timeout`: a number of milliseconds to execute `code` before terminating execution. If execution is terminated, an `Error` will be thrown. - -### script.runInContext(contextifiedSandbox[, options]) - -Similar to `vm.runInContext` but a method of a precompiled `Script` object. -`script.runInContext` runs `script`'s compiled code in `contextifiedSandbox` -and returns the result. Running code does not have access to local scope. - -`script.runInContext` takes the same options as `script.runInThisContext`. - -Example: compile code that increments a global variable and sets one, then -execute the code multiple times. These globals are contained in the sandbox. - - var util = require('util'); - var vm = require('vm'); - - var sandbox = { - animal: 'cat', - count: 2 - }; - - var context = new vm.createContext(sandbox); - var script = new vm.Script('count += 1; name = "kitty"'); - - for (var i = 0; i < 10; ++i) { - script.runInContext(context); - } - - console.log(util.inspect(sandbox)); - - // { animal: 'cat', count: 12, name: 'kitty' } - -Note that running untrusted code is a tricky business requiring great care. -`script.runInContext` is quite useful, but safely running untrusted code -requires a separate process. - - -### script.runInNewContext([sandbox][, options]) - -Similar to `vm.runInNewContext` but a method of a precompiled `Script` object. -`script.runInNewContext` contextifies `sandbox` if passed or creates a new -contextified sandbox if it's omitted, and then runs `script`'s compiled code -with the sandbox as the global object and returns the result. Running code does -not have access to local scope. - -`script.runInNewContext` takes the same options as `script.runInThisContext`. - -Example: compile code that sets a global variable, then execute the code -multiple times in different contexts. These globals are set on and contained in -the sandboxes. - - var util = require('util'); - var vm = require('vm'); - - var sandboxes = [{}, {}, {}]; - - var script = new vm.Script('globalVar = "set"'); - - sandboxes.forEach(function (sandbox) { - script.runInNewContext(sandbox); - }); - - console.log(util.inspect(sandboxes)); - - // [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] - -Note that running untrusted code is a tricky business requiring great care. -`script.runInNewContext` is quite useful, but safely running untrusted code -requires a separate process. +[1]: http://es5.github.io/#x10.4.2 From 8c83054fb8b65c9d0dcb95ca6e6d1ed9430bd80e Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:31:41 -0500 Subject: [PATCH 18/32] doc: sort url alphabetically Reorders, with no contextual changes, the url documentation alphabetically. --- doc/api/url.markdown | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/doc/api/url.markdown b/doc/api/url.markdown index cd4797777f07ec..8c8cd5bf1b85bf 100644 --- a/doc/api/url.markdown +++ b/doc/api/url.markdown @@ -77,20 +77,6 @@ properties of URL objects: The following methods are provided by the URL module: -## url.parse(urlStr[, parseQueryString][, slashesDenoteHost]) - -Take a URL string, and return an object. - -Pass `true` as the second argument to also parse the query string using the -`querystring` module. If `true` then the `query` property will always be -assigned an object, and the `search` property will always be a (possibly -empty) string. If `false` then the `query` property will not be parsed or -decoded. Defaults to `false`. - -Pass `true` as the third argument to treat `//foo/bar` as -`{ host: 'foo', pathname: '/bar' }` rather than -`{ pathname: '//foo/bar' }`. Defaults to `false`. - ## url.format(urlObj) Take a parsed URL object, and return a formatted URL string. @@ -117,6 +103,20 @@ Here's how the formatting process works: * It is treated the same with or without the leading `?` (question mark). * `hash` is treated the same with or without the leading `#` (pound sign, anchor). +## url.parse(urlStr[, parseQueryString][, slashesDenoteHost]) + +Take a URL string, and return an object. + +Pass `true` as the second argument to also parse the query string using the +`querystring` module. If `true` then the `query` property will always be +assigned an object, and the `search` property will always be a (possibly +empty) string. If `false` then the `query` property will not be parsed or +decoded. Defaults to `false`. + +Pass `true` as the third argument to treat `//foo/bar` as +`{ host: 'foo', pathname: '/bar' }` rather than +`{ pathname: '//foo/bar' }`. Defaults to `false`. + ## url.resolve(from, to) Take a base URL, and a href URL, and resolve them as a browser would for From cc6f224d268925168a47a5c500b8f92fad86325f Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:33:35 -0500 Subject: [PATCH 19/32] doc: sort tty alphabetically Reorders, with no contextual changes, the tty documentation alphabetically. --- doc/api/tty.markdown | 41 ++++++++++++++++++----------------------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/doc/api/tty.markdown b/doc/api/tty.markdown index 1a99041e60f486..acb3bb480bb774 100644 --- a/doc/api/tty.markdown +++ b/doc/api/tty.markdown @@ -15,18 +15,6 @@ in a TTY context is to check `process.stdout.isTTY`: $ node -p -e "Boolean(process.stdout.isTTY)" | cat false - -## tty.isatty(fd) - -Returns `true` or `false` depending on if the `fd` is associated with a -terminal. - - -## tty.setRawMode(mode) - - Stability: 0 - Deprecated: Use [tty.ReadStream#setRawMode][] (i.e. process.stdin.setRawMode) instead. - - ## Class: ReadStream A `net.Socket` subclass that represents the readable portion of a tty. In normal @@ -44,6 +32,7 @@ of the `tty.ReadStream` instance. `tty.ReadStream` to act either as a raw device or default. `isRaw` will be set to the resulting mode. +[tty.ReadStream#setRawMode]: #tty_rs_setrawmode_mode ## Class: WriteStream @@ -51,16 +40,6 @@ A `net.Socket` subclass that represents the writable portion of a tty. In normal circumstances, `process.stdout` will be the only `tty.WriteStream` instance ever created (and only when `isatty(1)` is true). -### ws.columns - -A `Number` that gives the number of columns the TTY currently has. This property -gets updated on "resize" events. - -### ws.rows - -A `Number` that gives the number of rows the TTY currently has. This property -gets updated on "resize" events. - ### Event: 'resize' `function () {}` @@ -73,5 +52,21 @@ has changed. console.log(process.stdout.columns + 'x' + process.stdout.rows); }); +### ws.columns -[tty.ReadStream#setRawMode]: #tty_rs_setrawmode_mode +A `Number` that gives the number of columns the TTY currently has. This property +gets updated on "resize" events. + +### ws.rows + +A `Number` that gives the number of rows the TTY currently has. This property +gets updated on "resize" events. + +## tty.isatty(fd) + +Returns `true` or `false` depending on if the `fd` is associated with a +terminal. + +## tty.setRawMode(mode) + + Stability: 0 - Deprecated: Use [tty.ReadStream#setRawMode][] (i.e. process.stdin.setRawMode) instead. From 15a8370cbbda332ac0f4168cd1ef48092c7edf6a Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:35:20 -0500 Subject: [PATCH 20/32] doc: sort timers alphabetically Reorders, with no contextual changes, the timers documentation alphabetically. --- doc/api/timers.markdown | 74 ++++++++++++++++++++--------------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/doc/api/timers.markdown b/doc/api/timers.markdown index 1dc456aaad925f..3a087be76a5cf2 100644 --- a/doc/api/timers.markdown +++ b/doc/api/timers.markdown @@ -5,25 +5,38 @@ All of the timer functions are globals. You do not need to `require()` this module in order to use them. -## setTimeout(callback, delay[, arg][, ...]) +## clearImmediate(immediateObject) -To schedule execution of a one-time `callback` after `delay` milliseconds. Returns a -`timeoutObject` for possible use with `clearTimeout()`. Optionally you can -also pass arguments to the callback. +Stops an immediate from triggering. -It is important to note that your callback will probably not be called in exactly -`delay` milliseconds - Node.js makes no guarantees about the exact timing of when -the callback will fire, nor of the ordering things will fire in. The callback will -be called as close as possible to the time specified. +## clearInterval(intervalObject) -To follow browser behavior, when using delays larger than 2147483647 -milliseconds (approximately 25 days) or less than 1, the timeout is executed -immediately, as if the `delay` was set to 1. +Stops an interval from triggering. ## clearTimeout(timeoutObject) Prevents a timeout from triggering. +## ref() + +If you had previously `unref()`d a timer you can call `ref()` to explicitly +request the timer hold the program open. If the timer is already `ref`d calling +`ref` again will have no effect. + +Returns the timer. + +## setImmediate(callback[, arg][, ...]) + +To schedule the "immediate" execution of `callback` after I/O events +callbacks and before `setTimeout` and `setInterval` . Returns an +`immediateObject` for possible use with `clearImmediate()`. Optionally you +can also pass arguments to the callback. + +Callbacks for immediates are queued in the order in which they were created. +The entire callback queue is processed every event loop iteration. If you queue +an immediate from inside an executing callback, that immediate won't fire +until the next event loop iteration. + ## setInterval(callback, delay[, arg][, ...]) To schedule the repeated execution of `callback` every `delay` milliseconds. @@ -34,9 +47,20 @@ To follow browser behavior, when using delays larger than 2147483647 milliseconds (approximately 25 days) or less than 1, Node.js will use 1 as the `delay`. -## clearInterval(intervalObject) +## setTimeout(callback, delay[, arg][, ...]) -Stops an interval from triggering. +To schedule execution of a one-time `callback` after `delay` milliseconds. Returns a +`timeoutObject` for possible use with `clearTimeout()`. Optionally you can +also pass arguments to the callback. + +It is important to note that your callback will probably not be called in exactly +`delay` milliseconds - Node.js makes no guarantees about the exact timing of when +the callback will fire, nor of the ordering things will fire in. The callback will +be called as close as possible to the time specified. + +To follow browser behavior, when using delays larger than 2147483647 +milliseconds (approximately 25 days) or less than 1, the timeout is executed +immediately, as if the `delay` was set to 1. ## unref() @@ -50,27 +74,3 @@ will wakeup the event loop, creating too many of these may adversely effect event loop performance -- use wisely. Returns the timer. - -## ref() - -If you had previously `unref()`d a timer you can call `ref()` to explicitly -request the timer hold the program open. If the timer is already `ref`d calling -`ref` again will have no effect. - -Returns the timer. - -## setImmediate(callback[, arg][, ...]) - -To schedule the "immediate" execution of `callback` after I/O events -callbacks and before `setTimeout` and `setInterval` . Returns an -`immediateObject` for possible use with `clearImmediate()`. Optionally you -can also pass arguments to the callback. - -Callbacks for immediates are queued in the order in which they were created. -The entire callback queue is processed every event loop iteration. If you queue -an immediate from inside an executing callback, that immediate won't fire -until the next event loop iteration. - -## clearImmediate(immediateObject) - -Stops an immediate from triggering. From da7afdcf6a4114e7768856df2588205f9f762e9a Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:36:11 -0500 Subject: [PATCH 21/32] doc: sort string_decoder alphabetically Reorders, with no contextual changes, the string_decode documentation alphabetically. --- doc/api/string_decoder.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/api/string_decoder.markdown b/doc/api/string_decoder.markdown index 4189923b9733c4..885af7745a23a0 100644 --- a/doc/api/string_decoder.markdown +++ b/doc/api/string_decoder.markdown @@ -19,10 +19,10 @@ additional support for utf8. Accepts a single argument, `encoding` which defaults to `utf8`. -### decoder.write(buffer) - -Returns a decoded string. - ### decoder.end() Returns any trailing bytes that were left in the buffer. + +### decoder.write(buffer) + +Returns a decoded string. From 059c98a6b02955cecd69ef74c1627be5d83fc5f7 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:38:09 -0500 Subject: [PATCH 22/32] doc: sort repl alphabetically Reorders, with no contextual changes, the repl documentation alphabetically. --- doc/api/repl.markdown | 187 +++++++++++++++++++++--------------------- 1 file changed, 93 insertions(+), 94 deletions(-) diff --git a/doc/api/repl.markdown b/doc/api/repl.markdown index 487749250b04d9..f298266ccb5d73 100644 --- a/doc/api/repl.markdown +++ b/doc/api/repl.markdown @@ -29,6 +29,21 @@ For example, you could add this to your bashrc file: alias node="env NODE_NO_READLINE=1 rlwrap node" +## Environment Variable Options + +The built-in repl (invoked by running `node` or `node -i`) may be controlled +via the following environment variables: + + - `NODE_REPL_HISTORY` - When a valid path is given, persistent REPL history + will be saved to the specified file rather than `.node_repl_history` in the + user's home directory. Setting this value to `""` will disable persistent + REPL history. + - `NODE_REPL_HISTORY_SIZE` - defaults to `1000`. Controls how many lines of + history will be persisted if history is available. Must be a positive number. + - `NODE_REPL_MODE` - may be any of `sloppy`, `strict`, or `magic`. Defaults + to `magic`, which will automatically run "strict mode only" statements in + strict mode. + ## Persistent History By default, the REPL will persist history between `node` REPL sessions by saving @@ -46,20 +61,86 @@ automatically be converted to using plain text. The new file will be saved to either your home directory, or a directory defined by the `NODE_REPL_HISTORY` variable, as documented below. -## Environment Variable Options +## REPL Features -The built-in repl (invoked by running `node` or `node -i`) may be controlled -via the following environment variables: + - - `NODE_REPL_HISTORY` - When a valid path is given, persistent REPL history - will be saved to the specified file rather than `.node_repl_history` in the - user's home directory. Setting this value to `""` will disable persistent - REPL history. - - `NODE_REPL_HISTORY_SIZE` - defaults to `1000`. Controls how many lines of - history will be persisted if history is available. Must be a positive number. - - `NODE_REPL_MODE` - may be any of `sloppy`, `strict`, or `magic`. Defaults - to `magic`, which will automatically run "strict mode only" statements in - strict mode. +Inside the REPL, Control+D will exit. Multi-line expressions can be input. +Tab completion is supported for both global and local variables. + +Core modules will be loaded on-demand into the environment. For example, +accessing `fs` will `require()` the `fs` module as `global.fs`. + +The special variable `_` (underscore) contains the result of the last expression. + + > [ 'a', 'b', 'c' ] + [ 'a', 'b', 'c' ] + > _.length + 3 + > _ += 1 + 4 + +The REPL provides access to any variables in the global scope. You can expose +a variable to the REPL explicitly by assigning it to the `context` object +associated with each `REPLServer`. For example: + + // repl_test.js + var repl = require('repl'), + msg = 'message'; + + repl.start('> ').context.m = msg; + +Things in the `context` object appear as local within the REPL: + + mjr:~$ node repl_test.js + > m + 'message' + +There are a few special REPL commands: + + - `.break` - While inputting a multi-line expression, sometimes you get lost + or just don't care about completing it. `.break` will start over. + - `.clear` - Resets the `context` object to an empty object and clears any + multi-line expression. + - `.exit` - Close the I/O stream, which will cause the REPL to exit. + - `.help` - Show this list of special commands. + - `.save` - Save the current REPL session to a file + >.save ./file/to/save.js + - `.load` - Load a file into the current REPL session. + >.load ./file/to/load.js + +The following key combinations in the REPL have these special effects: + + - `C` - Similar to the `.break` keyword. Terminates the current + command. Press twice on a blank line to forcibly exit. + - `D` - Similar to the `.exit` keyword. + - `` - Show both global and local(scope) variables + + +### Customizing Object displays in the REPL + +The REPL module internally uses +[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 + about this delegation [here][]. + +For example, if you have defined an `inspect()` function on an object, like this: + + > var obj = { foo: 'this will not show up in the inspect() output' }; + undefined + > obj.inspect = function() { + ... return { bar: 'baz' }; + ... }; + [Function] + +and try to print `obj` in REPL, it will invoke the custom `inspect()` function: + + > obj + { bar: 'baz' } + +[Readline Interface]: readline.html#readline_class_interface +[util.inspect()]: util.html#util_util_inspect_object_options +[here]: util.html#util_custom_inspect_function_on_objects ## repl.start(options) @@ -198,85 +279,3 @@ Example of listening for `reset`: console.log('repl has a new context'); someExtension.extend(context); }); - - -## REPL Features - - - -Inside the REPL, Control+D will exit. Multi-line expressions can be input. -Tab completion is supported for both global and local variables. - -Core modules will be loaded on-demand into the environment. For example, -accessing `fs` will `require()` the `fs` module as `global.fs`. - -The special variable `_` (underscore) contains the result of the last expression. - - > [ 'a', 'b', 'c' ] - [ 'a', 'b', 'c' ] - > _.length - 3 - > _ += 1 - 4 - -The REPL provides access to any variables in the global scope. You can expose -a variable to the REPL explicitly by assigning it to the `context` object -associated with each `REPLServer`. For example: - - // repl_test.js - var repl = require('repl'), - msg = 'message'; - - repl.start('> ').context.m = msg; - -Things in the `context` object appear as local within the REPL: - - mjr:~$ node repl_test.js - > m - 'message' - -There are a few special REPL commands: - - - `.break` - While inputting a multi-line expression, sometimes you get lost - or just don't care about completing it. `.break` will start over. - - `.clear` - Resets the `context` object to an empty object and clears any - multi-line expression. - - `.exit` - Close the I/O stream, which will cause the REPL to exit. - - `.help` - Show this list of special commands. - - `.save` - Save the current REPL session to a file - >.save ./file/to/save.js - - `.load` - Load a file into the current REPL session. - >.load ./file/to/load.js - -The following key combinations in the REPL have these special effects: - - - `C` - Similar to the `.break` keyword. Terminates the current - command. Press twice on a blank line to forcibly exit. - - `D` - Similar to the `.exit` keyword. - - `` - Show both global and local(scope) variables - - -### Customizing Object displays in the REPL - -The REPL module internally uses -[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 - about this delegation [here][]. - -For example, if you have defined an `inspect()` function on an object, like this: - - > var obj = { foo: 'this will not show up in the inspect() output' }; - undefined - > obj.inspect = function() { - ... return { bar: 'baz' }; - ... }; - [Function] - -and try to print `obj` in REPL, it will invoke the custom `inspect()` function: - - > obj - { bar: 'baz' } - -[Readline Interface]: readline.html#readline_class_interface -[util.inspect()]: util.html#util_util_inspect_object_options -[here]: util.html#util_custom_inspect_function_on_objects From 7ccad23156aa60d20371d8f88d5a39e21969bc18 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:43:06 -0500 Subject: [PATCH 23/32] doc: sort readline alphabetically Reorders, with no contextual changes, the readline documentation alphabetically. --- doc/api/readline.markdown | 211 +++++++++++++++++++------------------- 1 file changed, 105 insertions(+), 106 deletions(-) diff --git a/doc/api/readline.markdown b/doc/api/readline.markdown index 50ddaf660a87ac..ac5c61fa1cc9cf 100644 --- a/doc/api/readline.markdown +++ b/doc/api/readline.markdown @@ -23,75 +23,21 @@ program to gracefully exit: rl.close(); }); -## readline.createInterface(options) - -Creates a readline `Interface` instance. Accepts an "options" Object that takes -the following values: - - - `input` - the readable stream to listen to (Required). - - - `output` - the writable stream to write readline data to (Optional). - - - `completer` - an optional function that is used for Tab autocompletion. See - below for an example of using this. - - - `terminal` - pass `true` if the `input` and `output` streams should be - treated like a TTY, and have ANSI/VT100 escape codes written to it. - Defaults to checking `isTTY` on the `output` stream upon instantiation. - - - `historySize` - maximum number of history lines retained. Defaults to `30`. - -The `completer` function is given the current line entered by the user, and -is supposed to return an Array with 2 entries: - - 1. An Array with matching entries for the completion. - - 2. The substring that was used for the matching. - -Which ends up looking something like: -`[[substr1, substr2, ...], originalsubstring]`. - -Example: - - function completer(line) { - var completions = '.help .error .exit .quit .q'.split(' ') - var hits = completions.filter(function(c) { return c.indexOf(line) == 0 }) - // show all completions if none found - return [hits.length ? hits : completions, line] - } - -Also `completer` can be run in async mode if it accepts two arguments: - - function completer(linePartial, callback) { - callback(null, [['123'], linePartial]); - } - -`createInterface` is commonly used with `process.stdin` and -`process.stdout` in order to accept user input: - - var readline = require('readline'); - var rl = readline.createInterface({ - input: process.stdin, - output: process.stdout - }); - -Once you have a readline instance, you most commonly listen for the -`"line"` event. - -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 -a `"resize"` event on the `output` if/when the columns ever change -(`process.stdout` does this automatically when it is a TTY). - ## Class: Interface The class that represents a readline interface with an input and output stream. -### rl.setPrompt(prompt) +### rl.close() -Sets the prompt, for example when you run `node` on the command line, you see -`> `, which is node.js's prompt. +Closes the `Interface` instance, relinquishing control on the `input` and +`output` streams. The "close" event will also be emitted. + +### rl.pause() + +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`. ### rl.prompt([preserveCursor]) @@ -123,20 +69,14 @@ Example usage: console.log('Oh, so your favorite food is ' + answer); }); -### rl.pause() - -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`. - ### rl.resume() Resumes the readline `input` stream. -### rl.close() +### rl.setPrompt(prompt) -Closes the `Interface` instance, relinquishing control on the `input` and -`output` streams. The "close" event will also be emitted. +Sets the prompt, for example when you run `node` on the command line, you see +`> `, which is node.js's prompt. ### rl.write(data[, key]) @@ -154,6 +94,19 @@ Example: ## Events +### Event: 'close' + +`function () {}` + +Emitted when `close()` is called. + +Also emitted when the `input` stream receives its "end" event. The `Interface` +instance should be considered "finished" once this is emitted. For example, when +the `input` stream receives `^D`, respectively known as `EOT`. + +This event is also called if there is no `SIGINT` event listener present when +the `input` stream receives a `^C`, respectively known as `SIGINT`. + ### Event: 'line' `function (line) {}` @@ -194,18 +147,23 @@ Example of listening for `resume`: console.log('Readline resumed.'); }); -### Event: 'close' +### Event: 'SIGCONT' `function () {}` -Emitted when `close()` is called. +**This does not work on Windows.** -Also emitted when the `input` stream receives its "end" event. The `Interface` -instance should be considered "finished" once this is emitted. For example, when -the `input` stream receives `^D`, respectively known as `EOT`. +Emitted whenever the `input` stream is sent to the background with `^Z`, +respectively known as `SIGTSTP`, and then continued with `fg(1)`. This event +only emits if the stream was not paused before sending the program to the +background. -This event is also called if there is no `SIGINT` event listener present when -the `input` stream receives a `^C`, respectively known as `SIGINT`. +Example of listening for `SIGCONT`: + + rl.on('SIGCONT', function() { + // `prompt` will automatically resume the stream + rl.prompt(); + }); ### Event: 'SIGINT' @@ -247,25 +205,6 @@ Example of listening for `SIGTSTP`: console.log('Caught SIGTSTP.'); }); -### Event: 'SIGCONT' - -`function () {}` - -**This does not work on Windows.** - -Emitted whenever the `input` stream is sent to the background with `^Z`, -respectively known as `SIGTSTP`, and then continued with `fg(1)`. This event -only emits if the stream was not paused before sending the program to the -background. - -Example of listening for `SIGCONT`: - - rl.on('SIGCONT', function() { - // `prompt` will automatically resume the stream - rl.prompt(); - }); - - ## Example: Tiny CLI Here's an example of how to use all these together to craft a tiny command @@ -292,14 +231,6 @@ line interface: process.exit(0); }); -## readline.cursorTo(stream, x, y) - -Move cursor to the specified position in a given TTY stream. - -## readline.moveCursor(stream, dx, dy) - -Move cursor relative to it's current position in a given TTY stream. - ## readline.clearLine(stream, dir) Clears current line of given TTY stream in a specified direction. @@ -312,3 +243,71 @@ Clears current line of given TTY stream in a specified direction. ## readline.clearScreenDown(stream) Clears the screen from the current position of the cursor down. + +## readline.createInterface(options) + +Creates a readline `Interface` instance. Accepts an "options" Object that takes +the following values: + + - `input` - the readable stream to listen to (Required). + + - `output` - the writable stream to write readline data to (Optional). + + - `completer` - an optional function that is used for Tab autocompletion. See + below for an example of using this. + + - `terminal` - pass `true` if the `input` and `output` streams should be + treated like a TTY, and have ANSI/VT100 escape codes written to it. + Defaults to checking `isTTY` on the `output` stream upon instantiation. + + - `historySize` - maximum number of history lines retained. Defaults to `30`. + +The `completer` function is given the current line entered by the user, and +is supposed to return an Array with 2 entries: + + 1. An Array with matching entries for the completion. + + 2. The substring that was used for the matching. + +Which ends up looking something like: +`[[substr1, substr2, ...], originalsubstring]`. + +Example: + + function completer(line) { + var completions = '.help .error .exit .quit .q'.split(' ') + var hits = completions.filter(function(c) { return c.indexOf(line) == 0 }) + // show all completions if none found + return [hits.length ? hits : completions, line] + } + +Also `completer` can be run in async mode if it accepts two arguments: + + function completer(linePartial, callback) { + callback(null, [['123'], linePartial]); + } + +`createInterface` is commonly used with `process.stdin` and +`process.stdout` in order to accept user input: + + var readline = require('readline'); + var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout + }); + +Once you have a readline instance, you most commonly listen for the +`"line"` event. + +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 +a `"resize"` event on the `output` if/when the columns ever change +(`process.stdout` does this automatically when it is a TTY). + +## readline.cursorTo(stream, x, y) + +Move cursor to the specified position in a given TTY stream. + +## readline.moveCursor(stream, dx, dy) + +Move cursor relative to it's current position in a given TTY stream. From 89122cee4aee0255f6d90cf112b976235a533c04 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 12:50:07 -0500 Subject: [PATCH 24/32] doc: sort modules alphabetically Reorders, with no contextual changes, the modules documentation alphabetically. --- doc/api/modules.markdown | 478 +++++++++++++++++++-------------------- 1 file changed, 236 insertions(+), 242 deletions(-) diff --git a/doc/api/modules.markdown b/doc/api/modules.markdown index 57cd78b36b6738..8212bd07c67627 100644 --- a/doc/api/modules.markdown +++ b/doc/api/modules.markdown @@ -57,6 +57,169 @@ The `square` module is defined in `square.js`: The module system is implemented in the `require("module")` module. +## Accessing the main module + + + +When a file is run directly from Node.js, `require.main` is set to its +`module`. That means that you can determine whether a file has been run +directly by testing + + require.main === module + +For a file `foo.js`, this will be `true` if run via `node foo.js`, but +`false` if run by `require('./foo')`. + +Because `module` provides a `filename` property (normally equivalent to +`__filename`), the entry point of the current application can be obtained +by checking `require.main.filename`. + +## Addenda: Package Manager Tips + + + +The semantics of Node.js's `require()` function were designed to be general +enough to support a number of sane directory structures. Package manager +programs such as `dpkg`, `rpm`, and `npm` will hopefully find it possible to +build native packages from Node.js modules without modification. + +Below we give a suggested directory structure that could work: + +Let's say that we wanted to have the folder at +`/usr/lib/node//` hold the contents of a +specific version of a package. + +Packages can depend on one another. In order to install package `foo`, you +may have to install a specific version of package `bar`. The `bar` package +may itself have dependencies, and in some cases, these dependencies may even +collide or form cycles. + +Since Node.js looks up the `realpath` of any modules it loads (that is, +resolves symlinks), and then looks for their dependencies in the +`node_modules` folders as described above, this situation is very simple to +resolve with the following architecture: + +* `/usr/lib/node/foo/1.2.3/` - Contents of the `foo` package, version 1.2.3. +* `/usr/lib/node/bar/4.3.2/` - Contents of the `bar` package that `foo` + depends on. +* `/usr/lib/node/foo/1.2.3/node_modules/bar` - Symbolic link to + `/usr/lib/node/bar/4.3.2/`. +* `/usr/lib/node/bar/4.3.2/node_modules/*` - Symbolic links to the packages + that `bar` depends on. + +Thus, even if a cycle is encountered, or if there are dependency +conflicts, every module will be able to get a version of its dependency +that it can use. + +When the code in the `foo` package does `require('bar')`, it will get the +version that is symlinked into `/usr/lib/node/foo/1.2.3/node_modules/bar`. +Then, when the code in the `bar` package calls `require('quux')`, it'll get +the version that is symlinked into +`/usr/lib/node/bar/4.3.2/node_modules/quux`. + +Furthermore, to make the module lookup process even more optimal, rather +than putting packages directly in `/usr/lib/node`, we could put them in +`/usr/lib/node_modules//`. Then Node.js will not bother +looking for missing dependencies in `/usr/node_modules` or `/node_modules`. + +In order to make modules available to the Node.js REPL, it might be useful to +also add the `/usr/lib/node_modules` folder to the `$NODE_PATH` environment +variable. Since the module lookups using `node_modules` folders are all +relative, and based on the real path of the files making the calls to +`require()`, the packages themselves can be anywhere. + +## All Together... + + + +To get the exact filename that will be loaded when `require()` is called, use +the `require.resolve()` function. + +Putting together all of the above, here is the high-level algorithm +in pseudocode of what require.resolve does: + + require(X) from module at path Y + 1. If X is a core module, + a. return the core module + b. STOP + 2. If X begins with './' or '/' or '../' + a. LOAD_AS_FILE(Y + X) + b. LOAD_AS_DIRECTORY(Y + X) + 3. LOAD_NODE_MODULES(X, dirname(Y)) + 4. THROW "not found" + + LOAD_AS_FILE(X) + 1. If X is a file, load X as JavaScript text. STOP + 2. If X.js is a file, load X.js as JavaScript text. STOP + 3. If X.json is a file, parse X.json to a JavaScript Object. STOP + 4. If X.node is a file, load X.node as binary addon. STOP + + LOAD_AS_DIRECTORY(X) + 1. If X/package.json is a file, + a. Parse X/package.json, and look for "main" field. + b. let M = X + (json main field) + c. LOAD_AS_FILE(M) + 2. If X/index.js is a file, load X/index.js as JavaScript text. STOP + 3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP + 4. If X/index.node is a file, load X/index.node as binary addon. STOP + + LOAD_NODE_MODULES(X, START) + 1. let DIRS=NODE_MODULES_PATHS(START) + 2. for each DIR in DIRS: + a. LOAD_AS_FILE(DIR/X) + b. LOAD_AS_DIRECTORY(DIR/X) + + NODE_MODULES_PATHS(START) + 1. let PARTS = path split(START) + 2. let I = count of PARTS - 1 + 3. let DIRS = [] + 4. while I >= 0, + a. if PARTS[I] = "node_modules" CONTINUE + c. DIR = path join(PARTS[0 .. I] + "node_modules") + b. DIRS = DIRS + DIR + c. let I = I - 1 + 5. return DIRS + +## Caching + + + +Modules are cached after the first time they are loaded. This means +(among other things) that every call to `require('foo')` will get +exactly the same object returned, if it would resolve to the same file. + +Multiple calls to `require('foo')` may not cause the module code to be +executed multiple times. This is an important feature. With it, +"partially done" objects can be returned, thus allowing transitive +dependencies to be loaded even when they would cause cycles. + +If you want to have a module execute code multiple times, then export a +function, and call that function. + +### Module Caching Caveats + + + +Modules are cached based on their resolved filename. Since modules may +resolve to a different filename based on the location of the calling +module (loading from `node_modules` folders), it is not a *guarantee* +that `require('foo')` will always return the exact same object, if it +would resolve to different files. + +## Core Modules + + + +Node.js has several modules compiled into the binary. These modules are +described in greater detail elsewhere in this documentation. + +The core modules are defined within Node.js's source and are located in the +`lib/` folder. + +Core modules are always preferentially loaded if their identifier is +passed to `require()`. For instance, `require('http')` will always +return the built in HTTP module, even if there is a file by that name. + ## Cycles @@ -113,20 +276,6 @@ The output of this program would thus be: If you have cyclic module dependencies in your program, make sure to plan accordingly. -## Core Modules - - - -Node.js has several modules compiled into the binary. These modules are -described in greater detail elsewhere in this documentation. - -The core modules are defined within Node.js's source and are located in the -`lib/` folder. - -Core modules are always preferentially loaded if their identifier is -passed to `require()`. For instance, `require('http')` will always -return the built in HTTP module, even if there is a file by that name. - ## File Modules @@ -153,36 +302,6 @@ 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 `code` property set to `'MODULE_NOT_FOUND'`. -## Loading from `node_modules` Folders - - - -If the module identifier passed to `require()` is not a native module, -and does not begin with `'/'`, `'../'`, or `'./'`, then Node.js starts at the -parent directory of the current module, and adds `/node_modules`, and -attempts to load the module from that location. - -If it is not found there, then it moves to the parent directory, and so -on, until the root of the file system is reached. - -For example, if the file at `'/home/ry/projects/foo.js'` called -`require('bar.js')`, then Node.js would look in the following locations, in -this order: - -* `/home/ry/projects/node_modules/bar.js` -* `/home/ry/node_modules/bar.js` -* `/home/node_modules/bar.js` -* `/node_modules/bar.js` - -This allows programs to localize their dependencies, so that they do not -clash. - -You can require specific files or sub modules distributed with a module by -including a path suffix after the module name. For instance -`require('example-module/path/to/file')` would resolve `path/to/file` -relative to where `example-module` is located. The suffixed path follows the -same module resolution semantics. - ## Folders as Modules @@ -213,31 +332,69 @@ example, then `require('./some-library')` would attempt to load: * `./some-library/index.js` * `./some-library/index.node` -## Caching +## Loading from `node_modules` Folders -Modules are cached after the first time they are loaded. This means -(among other things) that every call to `require('foo')` will get -exactly the same object returned, if it would resolve to the same file. +If the module identifier passed to `require()` is not a native module, +and does not begin with `'/'`, `'../'`, or `'./'`, then Node.js starts at the +parent directory of the current module, and adds `/node_modules`, and +attempts to load the module from that location. -Multiple calls to `require('foo')` may not cause the module code to be -executed multiple times. This is an important feature. With it, -"partially done" objects can be returned, thus allowing transitive -dependencies to be loaded even when they would cause cycles. +If it is not found there, then it moves to the parent directory, and so +on, until the root of the file system is reached. -If you want to have a module execute code multiple times, then export a -function, and call that function. +For example, if the file at `'/home/ry/projects/foo.js'` called +`require('bar.js')`, then Node.js would look in the following locations, in +this order: -### Module Caching Caveats +* `/home/ry/projects/node_modules/bar.js` +* `/home/ry/node_modules/bar.js` +* `/home/node_modules/bar.js` +* `/node_modules/bar.js` - +This allows programs to localize their dependencies, so that they do not +clash. -Modules are cached based on their resolved filename. Since modules may -resolve to a different filename based on the location of the calling -module (loading from `node_modules` folders), it is not a *guarantee* -that `require('foo')` will always return the exact same object, if it -would resolve to different files. +You can require specific files or sub modules distributed with a module by +including a path suffix after the module name. For instance +`require('example-module/path/to/file')` would resolve `path/to/file` +relative to where `example-module` is located. The suffixed path follows the +same module resolution semantics. + +## Loading from the global folders + + + +If the `NODE_PATH` environment variable is set to a colon-delimited list +of absolute paths, then Node.js will search those paths for modules if they +are not found elsewhere. (Note: On Windows, `NODE_PATH` is delimited by +semicolons instead of colons.) + +`NODE_PATH` was originally created to support loading modules from +varying paths before the current +[module resolution](https://nodejs.org/api/modules.html#modules_all_together) +algorithm was frozen. + +`NODE_PATH` is still supported, but is less necessary now that the Node.js +ecosystem has settled on a convention for locating dependent modules. +Sometimes deployments that rely on `NODE_PATH` show surprising behavior +when people are unaware that `NODE_PATH` must be set. Sometimes a +module's dependencies change, causing a different version (or even a +different module) to be loaded as the `NODE_PATH` is searched. + +Additionally, Node.js will search in the following locations: + +* 1: `$HOME/.node_modules` +* 2: `$HOME/.node_libraries` +* 3: `$PREFIX/lib/node` + +Where `$HOME` is the user's home directory, and `$PREFIX` is Node.js's +configured `node_prefix`. + +These are mostly for historic reasons. **You are highly encouraged +to place your dependencies locally in `node_modules` folders.** They +will be loaded faster, and more reliably. ## The `module` Object @@ -251,6 +408,12 @@ representing the current module. For convenience, `module.exports` is also accessible via the `exports` module-global. `module` isn't actually a global but rather local to each module. +### module.children + +* {Array} + +The module objects required by this one. + ### module.exports * {Object} @@ -318,19 +481,11 @@ To illustrate the behavior, imagine this hypothetical implementation of As a guideline, if the relationship between `exports` and `module.exports` seems like magic to you, ignore `exports` and only use `module.exports`. -### module.require(id) - -* `id` {String} -* Return: {Object} `module.exports` from the resolved module - -The `module.require` method provides a way to load a module as if -`require()` was called from the original module. +### module.filename -Note that in order to do this, you must get a reference to the `module` -object. Since `require()` returns the `module.exports`, and the `module` is -typically *only* available within a specific module's code, it must be -explicitly exported in order to be used. +* {String} +The fully resolved filename to the module. ### module.id @@ -339,14 +494,6 @@ explicitly exported in order to be used. The identifier for the module. Typically this is the fully resolved filename. - -### module.filename - -* {String} - -The fully resolved filename to the module. - - ### module.loaded * {Boolean} @@ -354,174 +501,21 @@ The fully resolved filename to the module. Whether or not the module is done loading, or is in the process of loading. - ### module.parent * {Module Object} The module that first required this one. -### module.children - -* {Array} - -The module objects required by this one. - - - -## All Together... - - - -To get the exact filename that will be loaded when `require()` is called, use -the `require.resolve()` function. - -Putting together all of the above, here is the high-level algorithm -in pseudocode of what require.resolve does: - - require(X) from module at path Y - 1. If X is a core module, - a. return the core module - b. STOP - 2. If X begins with './' or '/' or '../' - a. LOAD_AS_FILE(Y + X) - b. LOAD_AS_DIRECTORY(Y + X) - 3. LOAD_NODE_MODULES(X, dirname(Y)) - 4. THROW "not found" - - LOAD_AS_FILE(X) - 1. If X is a file, load X as JavaScript text. STOP - 2. If X.js is a file, load X.js as JavaScript text. STOP - 3. If X.json is a file, parse X.json to a JavaScript Object. STOP - 4. If X.node is a file, load X.node as binary addon. STOP - - LOAD_AS_DIRECTORY(X) - 1. If X/package.json is a file, - a. Parse X/package.json, and look for "main" field. - b. let M = X + (json main field) - c. LOAD_AS_FILE(M) - 2. If X/index.js is a file, load X/index.js as JavaScript text. STOP - 3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP - 4. If X/index.node is a file, load X/index.node as binary addon. STOP - - LOAD_NODE_MODULES(X, START) - 1. let DIRS=NODE_MODULES_PATHS(START) - 2. for each DIR in DIRS: - a. LOAD_AS_FILE(DIR/X) - b. LOAD_AS_DIRECTORY(DIR/X) - - NODE_MODULES_PATHS(START) - 1. let PARTS = path split(START) - 2. let I = count of PARTS - 1 - 3. let DIRS = [] - 4. while I >= 0, - a. if PARTS[I] = "node_modules" CONTINUE - c. DIR = path join(PARTS[0 .. I] + "node_modules") - b. DIRS = DIRS + DIR - c. let I = I - 1 - 5. return DIRS - -## Loading from the global folders - - - -If the `NODE_PATH` environment variable is set to a colon-delimited list -of absolute paths, then Node.js will search those paths for modules if they -are not found elsewhere. (Note: On Windows, `NODE_PATH` is delimited by -semicolons instead of colons.) - -`NODE_PATH` was originally created to support loading modules from -varying paths before the current -[module resolution](https://nodejs.org/api/modules.html#modules_all_together) -algorithm was frozen. - -`NODE_PATH` is still supported, but is less necessary now that the Node.js -ecosystem has settled on a convention for locating dependent modules. -Sometimes deployments that rely on `NODE_PATH` show surprising behavior -when people are unaware that `NODE_PATH` must be set. Sometimes a -module's dependencies change, causing a different version (or even a -different module) to be loaded as the `NODE_PATH` is searched. - -Additionally, Node.js will search in the following locations: - -* 1: `$HOME/.node_modules` -* 2: `$HOME/.node_libraries` -* 3: `$PREFIX/lib/node` - -Where `$HOME` is the user's home directory, and `$PREFIX` is Node.js's -configured `node_prefix`. - -These are mostly for historic reasons. **You are highly encouraged -to place your dependencies locally in `node_modules` folders.** They -will be loaded faster, and more reliably. - -## Accessing the main module - - - -When a file is run directly from Node.js, `require.main` is set to its -`module`. That means that you can determine whether a file has been run -directly by testing - - require.main === module - -For a file `foo.js`, this will be `true` if run via `node foo.js`, but -`false` if run by `require('./foo')`. - -Because `module` provides a `filename` property (normally equivalent to -`__filename`), the entry point of the current application can be obtained -by checking `require.main.filename`. - -## Addenda: Package Manager Tips - - - -The semantics of Node.js's `require()` function were designed to be general -enough to support a number of sane directory structures. Package manager -programs such as `dpkg`, `rpm`, and `npm` will hopefully find it possible to -build native packages from Node.js modules without modification. - -Below we give a suggested directory structure that could work: - -Let's say that we wanted to have the folder at -`/usr/lib/node//` hold the contents of a -specific version of a package. - -Packages can depend on one another. In order to install package `foo`, you -may have to install a specific version of package `bar`. The `bar` package -may itself have dependencies, and in some cases, these dependencies may even -collide or form cycles. - -Since Node.js looks up the `realpath` of any modules it loads (that is, -resolves symlinks), and then looks for their dependencies in the -`node_modules` folders as described above, this situation is very simple to -resolve with the following architecture: - -* `/usr/lib/node/foo/1.2.3/` - Contents of the `foo` package, version 1.2.3. -* `/usr/lib/node/bar/4.3.2/` - Contents of the `bar` package that `foo` - depends on. -* `/usr/lib/node/foo/1.2.3/node_modules/bar` - Symbolic link to - `/usr/lib/node/bar/4.3.2/`. -* `/usr/lib/node/bar/4.3.2/node_modules/*` - Symbolic links to the packages - that `bar` depends on. - -Thus, even if a cycle is encountered, or if there are dependency -conflicts, every module will be able to get a version of its dependency -that it can use. +### module.require(id) -When the code in the `foo` package does `require('bar')`, it will get the -version that is symlinked into `/usr/lib/node/foo/1.2.3/node_modules/bar`. -Then, when the code in the `bar` package calls `require('quux')`, it'll get -the version that is symlinked into -`/usr/lib/node/bar/4.3.2/node_modules/quux`. +* `id` {String} +* Return: {Object} `module.exports` from the resolved module -Furthermore, to make the module lookup process even more optimal, rather -than putting packages directly in `/usr/lib/node`, we could put them in -`/usr/lib/node_modules//`. Then Node.js will not bother -looking for missing dependencies in `/usr/node_modules` or `/node_modules`. +The `module.require` method provides a way to load a module as if +`require()` was called from the original module. -In order to make modules available to the Node.js REPL, it might be useful to -also add the `/usr/lib/node_modules` folder to the `$NODE_PATH` environment -variable. Since the module lookups using `node_modules` folders are all -relative, and based on the real path of the files making the calls to -`require()`, the packages themselves can be anywhere. +Note that in order to do this, you must get a reference to the `module` +object. Since `require()` returns the `module.exports`, and the `module` is +typically *only* available within a specific module's code, it must be +explicitly exported in order to be used. From 35953273b0754497c78daea973d7c04a32b9d714 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 17:56:03 -0500 Subject: [PATCH 25/32] doc: sort http alphabetically Reorders, with no contextual changes, the http documentation alphabetically. --- doc/api/http.markdown | 1394 ++++++++++++++++++++--------------------- 1 file changed, 692 insertions(+), 702 deletions(-) diff --git a/doc/api/http.markdown b/doc/api/http.markdown index 8ac89b1f388a59..2e4775398c68dc 100644 --- a/doc/api/http.markdown +++ b/doc/api/http.markdown @@ -43,906 +43,747 @@ list like the following: 'Host', 'mysite.com', 'accepT', '*/*' ] -## http.METHODS - -* {Array} - -A list of the HTTP methods that are supported by the parser. - -## http.STATUS_CODES - -* {Object} - -A collection of all the standard HTTP response status codes, and the -short description of each. For example, `http.STATUS_CODES[404] === 'Not -Found'`. - -## http.createServer([requestListener]) - -Returns a new instance of [http.Server](#http_class_http_server). - -The `requestListener` is a function which is automatically -added to the `'request'` event. - -## http.createClient([port][, host]) - - Stability: 0 - Deprecated: Use [http.request][] instead. - -Constructs a new HTTP client. `port` and `host` refer to the server to be -connected to. - -## Class: http.Server - -This is an [EventEmitter][] with the following events: - -### Event: 'request' - -`function (request, response) { }` - -Emitted each time there is a request. Note that there may be multiple requests -per connection (in the case of keep-alive connections). - `request` is an instance of [http.IncomingMessage][] and `response` is -an instance of [http.ServerResponse][]. - -### Event: 'connection' - -`function (socket) { }` - -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 -particular, the socket will not emit `readable` events because of how -the protocol parser attaches to the socket. The `socket` can also be -accessed at `request.connection`. - -### Event: 'close' - -`function () { }` - -Emitted when the server closes. - -### Event: 'checkContinue' - -`function (request, response) { }` - -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 -with a 100 Continue as appropriate. - -Handling this event involves calling [response.writeContinue()][] if the client -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 -request body. - -Note that when this event is emitted and handled, the `request` event will -not be emitted. - -### Event: 'connect' - -`function (request, socket, head) { }` - -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 -connections closed. - -* `request` is the arguments for the http request, as it is in the request - event. -* `socket` is the network socket between the server and client. -* `head` is an instance of Buffer, the first packet of the tunneling stream, - this may be empty. - -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 -sent to the server on that socket. - -### Event: 'upgrade' - -`function (request, socket, head) { }` - -Emitted each time a client requests a http upgrade. If this event isn't -listened for, then clients requesting an upgrade will have their connections -closed. - -* `request` is the arguments for the http request, as it is in the request - event. -* `socket` is the network socket between the server and client. -* `head` is an instance of Buffer, the first packet of the upgraded stream, - this may be empty. - -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 -sent to the server on that socket. - -### Event: 'clientError' - -`function (exception, socket) { }` - -If a client connection emits an 'error' event, it will be forwarded here. - -`socket` is the `net.Socket` object that the error originated from. - - -### server.listen(port[, hostname][, backlog][, callback]) +## Class: http.Agent -Begin accepting connections on the specified `port` and `hostname`. If the -`hostname` is omitted, the server will accept connections on any IPv6 address -(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A -port value of zero will assign a random port. +The HTTP Agent is used for pooling sockets used in HTTP client +requests. -To listen to a unix socket, supply a filename instead of port and hostname. +The HTTP Agent also defaults client requests to using +Connection:keep-alive. If no pending HTTP requests are waiting on a +socket to become free the socket is closed. This means that Node.js's +pool has the benefit of keep-alive when under load but still does not +require developers to manually close the HTTP clients using +KeepAlive. -Backlog is the maximum length of the queue of pending connections. -The actual length will be determined by your OS through sysctl settings such as -`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this -parameter is 511 (not 512). +If you opt into using HTTP KeepAlive, you can create an Agent object +with that flag set to `true`. (See the [constructor +options](#http_new_agent_options) below.) Then, the Agent will keep +unused sockets in a pool for later use. They will be explicitly +marked so as to not keep the Node.js process running. However, it is +still a good idea to explicitly [`destroy()`](#http_agent_destroy) +KeepAlive agents when they are no longer in use, so that the Sockets +will be shut down. -This function is asynchronous. The last parameter `callback` will be added as -a listener for the ['listening'][] event. See also [net.Server.listen(port)][]. +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 +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: + http.get(options, function(res) { + // Do stuff + }).on("socket", function (socket) { + socket.emit("agentRemove"); + }); -### server.listen(path[, callback]) +Alternatively, you could just opt out of pooling entirely using +`agent:false`: -Start a UNIX socket server listening for connections on the given `path`. + http.get({ + hostname: 'localhost', + port: 80, + path: '/', + agent: false // create a new agent just for this one request + }, function (res) { + // Do stuff with response + }) -This function is asynchronous. The last parameter `callback` will be added as -a listener for the ['listening'][] event. See also [net.Server.listen(path)][]. +### new Agent([options]) +* `options` {Object} Set of configurable options to set on the agent. + Can have the following fields: + * `keepAlive` {Boolean} Keep sockets around in a pool to be used by + other requests in the future. Default = `false` + * `keepAliveMsecs` {Integer} When using HTTP KeepAlive, how often + to send TCP KeepAlive packets over sockets being kept alive. + Default = `1000`. Only relevant if `keepAlive` is set to `true`. + * `maxSockets` {Number} Maximum number of sockets to allow per + host. Default = `Infinity`. + * `maxFreeSockets` {Number} Maximum number of sockets to leave open + in a free state. Only relevant if `keepAlive` is set to `true`. + Default = `256`. -### server.listen(handle[, callback]) +The default `http.globalAgent` that is used by `http.request` has all +of these values set to their respective defaults. -* `handle` {Object} -* `callback` {Function} +To configure any of them, you must create your own `Agent` object. -The `handle` object can be set to either a server or socket (anything -with an underlying `_handle` member), or a `{fd: }` object. +```javascript +var http = require('http'); +var keepAliveAgent = new http.Agent({ keepAlive: true }); +options.agent = keepAliveAgent; +http.request(options, onResponseCallback); +``` -This will cause the server to accept connections on the specified -handle, but it is presumed that the file descriptor or handle has -already been bound to a port or domain socket. +### agent.destroy() -Listening on a file descriptor is not supported on Windows. +Destroy any sockets that are currently in use by the agent. -This function is asynchronous. The last parameter `callback` will be added as -a listener for the ['listening'](net.html#net_event_listening) event. -See also [net.Server.listen()](net.html#net_server_listen_handle_callback). +It is usually not necessary to do this. However, if you are using an +agent with KeepAlive enabled, then it is best to explicitly shut down +the agent when you know that it will no longer be used. Otherwise, +sockets may hang open for quite a long time before the server +terminates them. -### server.close([callback]) +### agent.freeSockets -Stops the server from accepting new connections. See [net.Server.close()][]. +An object which contains arrays of sockets currently awaiting use by +the Agent when HTTP KeepAlive is used. Do not modify. +### agent.getName(options) -### server.maxHeadersCount +Get a unique name for a set of request options, to determine whether a +connection can be reused. In the http agent, this returns +`host:port:localAddress`. In the https agent, the name includes the +CA, cert, ciphers, and other HTTPS/TLS-specific options that determine +socket reusability. -Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - -no limit will be applied. +### agent.maxFreeSockets -### server.setTimeout(msecs, callback) +By default set to 256. For Agents supporting HTTP KeepAlive, this +sets the maximum number of sockets that will be left open in the free +state. -* `msecs` {Number} -* `callback` {Function} +### agent.maxSockets -Sets the timeout value for sockets, and emits a `'timeout'` event on -the Server object, passing the socket as an argument, if a timeout -occurs. +By default set to Infinity. Determines how many concurrent sockets the agent +can have open per origin. Origin is either a 'host:port' or +'host:port:localAddress' combination. -If there is a `'timeout'` event listener on the Server object, then it -will be called with the timed-out socket as an argument. +### agent.requests -By default, the Server's timeout value is 2 minutes, and sockets are -destroyed automatically if they time out. However, if you assign a -callback to the Server's `'timeout'` event, then you are responsible -for handling socket timeouts. +An object which contains queues of requests that have not yet been assigned to +sockets. Do not modify. -Returns `server`. +### agent.sockets -### server.timeout +An object which contains arrays of sockets currently in use by the +Agent. Do not modify. -* {Number} Default = 120000 (2 minutes) +## Class: http.ClientRequest -The number of milliseconds of inactivity before a socket is presumed -to have timed out. +This object is created internally and returned from `http.request()`. It +represents an _in-progress_ request whose header has already been queued. The +header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, +`removeHeader(name)` API. The actual header will be sent along with the first +data chunk or when closing the connection. -Note that the socket timeout logic is set up on connection, so -changing this value only affects *new* connections to the server, not -any existing connections. +To get the response, add a listener for `'response'` to the request object. +`'response'` will be emitted from the request object when the response +headers have been received. The `'response'` event is executed with one +argument which is an instance of [http.IncomingMessage][]. -Set to 0 to disable any kind of automatic timeout behavior on incoming -connections. +During the `'response'` event, one can add listeners to the +response object; particularly to listen for the `'data'` event. -## Class: http.ServerResponse +If no `'response'` handler is added, then the response will be +entirely discarded. However, if you add a `'response'` event handler, +then you **must** consume the data from the response object, either by +calling `response.read()` whenever there is a `'readable'` event, or +by adding a `'data'` handler, or by calling the `.resume()` method. +Until the data is consumed, the `'end'` event will not fire. Also, until +the data is read it will consume memory that can eventually lead to a +'process out of memory' error. -This object is created internally by a HTTP server--not by the user. It is -passed as the second parameter to the `'request'` event. +Note: Node.js does not check whether Content-Length and the length of the body +which has been transmitted are equal or not. -The response implements the [Writable Stream][] interface. This is an +The request implements the [Writable Stream][] interface. This is an [EventEmitter][] with the following events: -### Event: 'close' - -`function () { }` - -Indicates that the underlying connection was terminated before -[response.end()][] was called or able to flush. - -### Event: 'finish' +### Event: 'abort' `function () { }` -Emitted when the response has been sent. More specifically, this event is -emitted when the last segment of the response headers and body have been -handed off to the operating system for transmission over the network. It -does not imply that the client has received anything yet. - -After this event, no more events will be emitted on the response object. - -### response.writeContinue() +Emitted when the request has been aborted by the client. This event is only +emitted on the first call to `abort()`. -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`. +### Event: 'connect' -### response.writeHead(statusCode[, statusMessage][, headers]) +`function (response, socket, head) { }` -Sends a response header to the request. The status code is a 3-digit HTTP -status code, like `404`. The last argument, `headers`, are the response headers. -Optionally one can give a human-readable `statusMessage` as the second -argument. +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 +their connections closed. -Example: +A client server pair that show you how to listen for the `connect` event. - var body = 'hello world'; - response.writeHead(200, { - 'Content-Length': body.length, - 'Content-Type': 'text/plain' }); + var http = require('http'); + var net = require('net'); + var url = require('url'); -This method must only be called once on a message and it must -be called before [response.end()][] is called. + // Create an HTTP tunneling proxy + var proxy = http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('okay'); + }); + proxy.on('connect', function(req, cltSocket, head) { + // connect to an origin server + var srvUrl = url.parse('http://' + req.url); + var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() { + cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + + 'Proxy-agent: Node.js-Proxy\r\n' + + '\r\n'); + srvSocket.write(head); + srvSocket.pipe(cltSocket); + cltSocket.pipe(srvSocket); + }); + }); -If you call [response.write()][] or [response.end()][] before calling this, the -implicit/mutable headers will be calculated and call this function for you. + // now that proxy is running + proxy.listen(1337, '127.0.0.1', function() { -Note that Content-Length is given in bytes not characters. The above example -works because the string `'hello world'` contains only single byte characters. -If the body contains higher coded characters then `Buffer.byteLength()` -should be used to determine the number of bytes in a given encoding. -And Node.js does not check whether Content-Length and the length of the body -which has been transmitted are equal or not. + // make a request to a tunneling proxy + var options = { + port: 1337, + hostname: '127.0.0.1', + method: 'CONNECT', + path: 'www.google.com:80' + }; -### response.setTimeout(msecs, callback) + var req = http.request(options); + req.end(); -* `msecs` {Number} -* `callback` {Function} + req.on('connect', function(res, socket, head) { + console.log('got connected!'); -Sets the Socket's timeout value to `msecs`. If a callback is -provided, then it is added as a listener on the `'timeout'` event on -the response object. + // make a request over an HTTP tunnel + socket.write('GET / HTTP/1.1\r\n' + + 'Host: www.google.com:80\r\n' + + 'Connection: close\r\n' + + '\r\n'); + socket.on('data', function(chunk) { + console.log(chunk.toString()); + }); + socket.on('end', function() { + proxy.close(); + }); + }); + }); -If no `'timeout'` listener is added to the request, the response, or -the server, then sockets are destroyed when they time out. If you -assign a handler on the request, the response, or the server's -`'timeout'` events, then it is your responsibility to handle timed out -sockets. +### Event: 'continue' -Returns `response`. +`function () { }` -### response.statusCode +Emitted when the server sends a '100 Continue' HTTP response, usually because +the request contained 'Expect: 100-continue'. This is an instruction that +the client should send the request body. -When using implicit headers (not calling [response.writeHead()][] explicitly), -this property controls the status code that will be sent to the client when -the headers get flushed. +### Event: 'response' -Example: +`function (response) { }` - response.statusCode = 404; +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][]. -After response header was sent to the client, this property indicates the -status code which was sent out. +Options: -### response.statusMessage +- `host`: A domain name or IP address of the server to issue the request to. +- `port`: Port of remote server. +- `socketPath`: Unix Domain Socket (use one of host:port or socketPath) -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 -flushed. If this is left as `undefined` then the standard message for the status -code will be used. +### Event: 'socket' -Example: +`function (socket) { }` - response.statusMessage = 'Not found'; +Emitted after a socket is assigned to this request. -After response header was sent to the client, this property indicates the -status message which was sent out. +### Event: 'upgrade' -### response.setHeader(name, value) +`function (response, socket, head) { }` -Sets a single header value for implicit headers. If this header already exists -in the to-be-sent headers, its value will be replaced. Use an array of strings -here if you need to send multiple headers with the same name. +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 +their connections closed. -Example: +A client server pair that show you how to listen for the `upgrade` event. - response.setHeader("Content-Type", "text/html"); + var http = require('http'); -or + // Create an HTTP server + var srv = http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('okay'); + }); + srv.on('upgrade', function(req, socket, head) { + socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + + 'Upgrade: WebSocket\r\n' + + 'Connection: Upgrade\r\n' + + '\r\n'); - response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]); + socket.pipe(socket); // echo back + }); -Attempting to set a header field name that contains invalid characters will -result in a `TypeError` being thrown. + // now that server is running + srv.listen(1337, '127.0.0.1', function() { -### response.headersSent + // make a request + var options = { + port: 1337, + hostname: '127.0.0.1', + headers: { + 'Connection': 'Upgrade', + 'Upgrade': 'websocket' + } + }; -Boolean (read-only). True if headers were sent, false otherwise. + var req = http.request(options); + req.end(); -### response.sendDate + req.on('upgrade', function(res, socket, upgradeHead) { + console.log('got upgraded!'); + socket.end(); + process.exit(0); + }); + }); -When true, the Date header will be automatically generated and sent in -the response if it is not already present in the headers. Defaults to true. +### request.abort() -This should only be disabled for testing; HTTP requires the Date header -in responses. +Marks the request as aborting. Calling this will cause remaining data +in the response to be dropped and the socket to be destroyed. -### response.getHeader(name) +### request.end([data][, encoding][, callback]) -Reads out a header that's already been queued but not sent to the client. Note -that the name is case insensitive. This can only be called before headers get -implicitly flushed. +Finishes sending the request. If any parts of the body are +unsent, it will flush them to the stream. If the request is +chunked, this will send the terminating `'0\r\n\r\n'`. -Example: +If `data` is specified, it is equivalent to calling +`request.write(data, encoding)` followed by `request.end(callback)`. - var contentType = response.getHeader('content-type'); +If `callback` is specified, it will be called when the request stream +is finished. -### response.removeHeader(name) +### request.flushHeaders() -Removes a header that's queued for implicit sending. +Flush the request headers. -Example: +For efficiency reasons, Node.js normally buffers the request headers until you +call `request.end()` or write the first chunk of request data. It then tries +hard to pack the request headers and data into a single TCP packet. - response.removeHeader("Content-Encoding"); +That's usually what you want (it saves a TCP round-trip) but not when the first +data isn't sent until possibly much later. `request.flushHeaders()` lets you bypass +the optimization and kickstart the request. +### request.setNoDelay([noDelay]) -### response.write(chunk[, encoding][, callback]) +Once a socket is assigned to this request and is connected +[socket.setNoDelay()][] will be 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. +### request.setSocketKeepAlive([enable][, initialDelay]) -This sends a chunk of the response body. This method may -be called multiple times to provide successive parts of the body. +Once a socket is assigned to this request and is connected +[socket.setKeepAlive()][] will be called. -`chunk` can be a string or a buffer. If `chunk` is a string, -the second parameter specifies how to encode it into a byte stream. -By default the `encoding` is `'utf8'`. The last parameter `callback` -will be called when this chunk of data is flushed. +### request.setTimeout(timeout[, callback]) -**Note**: This is the raw HTTP body and has nothing to do with -higher-level multi-part body encodings that may be used. +Once a socket is assigned to this request and is connected +[socket.setTimeout()][] will be called. -The first time `response.write()` is called, it will send the buffered -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 -data, and sends that separately. That is, the response is buffered up to the -first chunk of body. +### request.write(chunk[, encoding][, callback]) -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. -`'drain'` will be emitted when the buffer is free again. +Sends a chunk of the body. By calling this method +many times, the user can stream a request body to a +server--in that case it is suggested to use the +`['Transfer-Encoding', 'chunked']` header line when +creating the request. -### response.addTrailers(headers) +The `chunk` argument should be a [Buffer][] or a string. -This method adds HTTP trailing headers (a header but at the end of the -message) to the response. +The `encoding` argument is optional and only applies when `chunk` is a string. +Defaults to `'utf8'`. -Trailers will **only** be emitted if chunked encoding is used for the -response; if it is not (e.g., if the request was HTTP/1.0), they will -be silently discarded. +The `callback` argument is optional and will be called when this chunk of data +is flushed. -Note that HTTP requires the `Trailer` header to be sent if you intend to -emit trailers, with a list of the header fields in its value. E.g., +Returns `request`. - response.writeHead(200, { 'Content-Type': 'text/plain', - 'Trailer': 'Content-MD5' }); - response.write(fileData); - response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"}); - response.end(); +## Class: http.Server -Attempting to set a trailer field name that contains invalid characters will -result in a `TypeError` being thrown. +This is an [EventEmitter][] with the following events: -### response.end([data][, encoding][, callback]) +### Event: 'checkContinue' -This method signals to the server that all of the response headers and body -have been sent; that server should consider this message complete. -The method, `response.end()`, MUST be called on each -response. +`function (request, response) { }` -If `data` is specified, it is equivalent to calling -`response.write(data, encoding)` followed by `response.end(callback)`. +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 +with a 100 Continue as appropriate. -If `callback` is specified, it will be called when the response stream -is finished. +Handling this event involves calling [response.writeContinue()][] if the client +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 +request body. -### response.finished +Note that when this event is emitted and handled, the `request` event will +not be emitted. -Boolean value that indicates whether the response has completed. Starts -as `false`. After `response.end()` executes, the value will be `true`. +### Event: 'clientError' -## http.request(options[, callback]) +`function (exception, socket) { }` -Node.js maintains several connections per server to make HTTP requests. -This function allows one to transparently issue requests. +If a client connection emits an 'error' event, it will be forwarded here. -`options` can be an object or a string. If `options` is a string, it is -automatically parsed with [url.parse()][]. +`socket` is the `net.Socket` object that the error originated from. -Options: +### Event: 'close' -- `protocol`: Protocol to use. Defaults to `'http'`. -- `host`: A domain name or IP address of the server to issue the request to. - Defaults to `'localhost'`. -- `hostname`: Alias for `host`. To support `url.parse()` `hostname` is - preferred over `host`. -- `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 - used. -- `port`: Port of remote server. Defaults to 80. -- `localAddress`: Local interface to bind for network connections. -- `socketPath`: Unix Domain Socket (use one of host:port or socketPath). -- `method`: A string specifying the HTTP request method. Defaults to `'GET'`. -- `path`: Request path. Defaults to `'/'`. Should include query string if any. - E.G. `'/index.html?page=12'`. An exception is thrown when the request path - contains illegal characters. Currently, only spaces are rejected but that - may change in the future. -- `headers`: An object containing request headers. -- `auth`: Basic authentication i.e. `'user:password'` to compute an - Authorization header. -- `agent`: Controls [Agent][] behavior. When an Agent is used request will - default to `Connection: keep-alive`. Possible values: - - `undefined` (default): use [globalAgent][] for this host and port. - - `Agent` object: explicitly use the passed in `Agent`. - - `false`: opts out of connection pooling with an Agent, defaults request to - `Connection: close`. +`function () { }` -The optional `callback` parameter will be added as a one time listener for -the ['response'][] event. +Emitted when the server closes. -`http.request()` returns an instance of the [http.ClientRequest][] -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. +### Event: 'connect' -Example: +`function (request, socket, head) { }` - var postData = querystring.stringify({ - 'msg' : 'Hello World!' - }); +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 +connections closed. - var options = { - hostname: 'www.google.com', - port: 80, - path: '/upload', - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'Content-Length': postData.length - } - }; +* `request` is the arguments for the http request, as it is in the request + event. +* `socket` is the network socket between the server and client. +* `head` is an instance of Buffer, the first packet of the tunneling stream, + this may be empty. - var req = http.request(options, function(res) { - console.log('STATUS: ' + res.statusCode); - console.log('HEADERS: ' + JSON.stringify(res.headers)); - res.setEncoding('utf8'); - res.on('data', function (chunk) { - console.log('BODY: ' + chunk); - }); - res.on('end', function() { - console.log('No more data in response.') - }) - }); +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 +sent to the server on that socket. - req.on('error', function(e) { - console.log('problem with request: ' + e.message); - }); +### Event: 'connection' - // write data to request body - req.write(postData); - req.end(); +`function (socket) { }` -Note that in the example `req.end()` was called. With `http.request()` one -must always call `req.end()` to signify that you're done with the request - -even if there is no data being written to the request body. +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 +particular, the socket will not emit `readable` events because of how +the protocol parser attaches to the socket. The `socket` can also be +accessed at `request.connection`. -If any error is encountered during the request (be that with DNS resolution, -TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted -on the returned request object. +### Event: 'request' -There are a few special headers that should be noted. +`function (request, response) { }` -* Sending a 'Connection: keep-alive' will notify Node.js that the connection to - the server should be persisted until the next request. +Emitted each time there is a request. Note that there may be multiple requests +per connection (in the case of keep-alive connections). + `request` is an instance of [http.IncomingMessage][] and `response` is +an instance of [http.ServerResponse][]. -* Sending a 'Content-length' header will disable the default chunked encoding. +### Event: 'upgrade' -* Sending an 'Expect' header will immediately send the request headers. - 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 - information. +`function (request, socket, head) { }` -* Sending an Authorization header will override using the `auth` option - to compute basic authentication. +Emitted each time a client requests a http upgrade. If this event isn't +listened for, then clients requesting an upgrade will have their connections +closed. -## http.get(options[, callback]) +* `request` is the arguments for the http request, as it is in the request + event. +* `socket` is the network socket between the server and client. +* `head` is an instance of Buffer, the first packet of the upgraded stream, + this may be empty. -Since most requests are GET requests without bodies, Node.js provides this -convenience method. The only difference between this method and `http.request()` -is that it sets the method to GET and calls `req.end()` automatically. +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 +sent to the server on that socket. -Example: +### server.close([callback]) - http.get("http://www.google.com/index.html", function(res) { - console.log("Got response: " + res.statusCode); - }).on('error', function(e) { - console.log("Got error: " + e.message); - }); +Stops the server from accepting new connections. See [net.Server.close()][]. +### server.listen(handle[, callback]) -## Class: http.Agent +* `handle` {Object} +* `callback` {Function} -The HTTP Agent is used for pooling sockets used in HTTP client -requests. +The `handle` object can be set to either a server or socket (anything +with an underlying `_handle` member), or a `{fd: }` object. -The HTTP Agent also defaults client requests to using -Connection:keep-alive. If no pending HTTP requests are waiting on a -socket to become free the socket is closed. This means that Node.js's -pool has the benefit of keep-alive when under load but still does not -require developers to manually close the HTTP clients using -KeepAlive. +This will cause the server to accept connections on the specified +handle, but it is presumed that the file descriptor or handle has +already been bound to a port or domain socket. -If you opt into using HTTP KeepAlive, you can create an Agent object -with that flag set to `true`. (See the [constructor -options](#http_new_agent_options) below.) Then, the Agent will keep -unused sockets in a pool for later use. They will be explicitly -marked so as to not keep the Node.js process running. However, it is -still a good idea to explicitly [`destroy()`](#http_agent_destroy) -KeepAlive agents when they are no longer in use, so that the Sockets -will be shut down. +Listening on a file descriptor is not supported on Windows. -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 -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: +This function is asynchronous. The last parameter `callback` will be added as +a listener for the ['listening'](net.html#net_event_listening) event. +See also [net.Server.listen()](net.html#net_server_listen_handle_callback). - http.get(options, function(res) { - // Do stuff - }).on("socket", function (socket) { - socket.emit("agentRemove"); - }); +### server.listen(path[, callback]) -Alternatively, you could just opt out of pooling entirely using -`agent:false`: +Start a UNIX socket server listening for connections on the given `path`. - http.get({ - hostname: 'localhost', - port: 80, - path: '/', - agent: false // create a new agent just for this one request - }, function (res) { - // Do stuff with response - }) +This function is asynchronous. The last parameter `callback` will be added as +a listener for the ['listening'][] event. See also [net.Server.listen(path)][]. -### new Agent([options]) +### server.listen(port[, hostname][, backlog][, callback]) -* `options` {Object} Set of configurable options to set on the agent. - Can have the following fields: - * `keepAlive` {Boolean} Keep sockets around in a pool to be used by - other requests in the future. Default = `false` - * `keepAliveMsecs` {Integer} When using HTTP KeepAlive, how often - to send TCP KeepAlive packets over sockets being kept alive. - Default = `1000`. Only relevant if `keepAlive` is set to `true`. - * `maxSockets` {Number} Maximum number of sockets to allow per - host. Default = `Infinity`. - * `maxFreeSockets` {Number} Maximum number of sockets to leave open - in a free state. Only relevant if `keepAlive` is set to `true`. - Default = `256`. +Begin accepting connections on the specified `port` and `hostname`. If the +`hostname` is omitted, the server will accept connections on any IPv6 address +(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A +port value of zero will assign a random port. -The default `http.globalAgent` that is used by `http.request` has all -of these values set to their respective defaults. +To listen to a unix socket, supply a filename instead of port and hostname. -To configure any of them, you must create your own `Agent` object. +Backlog is the maximum length of the queue of pending connections. +The actual length will be determined by your OS through sysctl settings such as +`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this +parameter is 511 (not 512). -```javascript -var http = require('http'); -var keepAliveAgent = new http.Agent({ keepAlive: true }); -options.agent = keepAliveAgent; -http.request(options, onResponseCallback); -``` +This function is asynchronous. The last parameter `callback` will be added as +a listener for the ['listening'][] event. See also [net.Server.listen(port)][]. -### agent.maxSockets +### server.maxHeadersCount -By default set to Infinity. Determines how many concurrent sockets the agent -can have open per origin. Origin is either a 'host:port' or -'host:port:localAddress' combination. +Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - +no limit will be applied. -### agent.maxFreeSockets +### server.setTimeout(msecs, callback) -By default set to 256. For Agents supporting HTTP KeepAlive, this -sets the maximum number of sockets that will be left open in the free -state. +* `msecs` {Number} +* `callback` {Function} -### agent.sockets +Sets the timeout value for sockets, and emits a `'timeout'` event on +the Server object, passing the socket as an argument, if a timeout +occurs. -An object which contains arrays of sockets currently in use by the -Agent. Do not modify. +If there is a `'timeout'` event listener on the Server object, then it +will be called with the timed-out socket as an argument. -### agent.freeSockets +By default, the Server's timeout value is 2 minutes, and sockets are +destroyed automatically if they time out. However, if you assign a +callback to the Server's `'timeout'` event, then you are responsible +for handling socket timeouts. -An object which contains arrays of sockets currently awaiting use by -the Agent when HTTP KeepAlive is used. Do not modify. +Returns `server`. -### agent.requests +### server.timeout -An object which contains queues of requests that have not yet been assigned to -sockets. Do not modify. +* {Number} Default = 120000 (2 minutes) -### agent.destroy() +The number of milliseconds of inactivity before a socket is presumed +to have timed out. -Destroy any sockets that are currently in use by the agent. +Note that the socket timeout logic is set up on connection, so +changing this value only affects *new* connections to the server, not +any existing connections. -It is usually not necessary to do this. However, if you are using an -agent with KeepAlive enabled, then it is best to explicitly shut down -the agent when you know that it will no longer be used. Otherwise, -sockets may hang open for quite a long time before the server -terminates them. +Set to 0 to disable any kind of automatic timeout behavior on incoming +connections. -### agent.getName(options) +## Class: http.ServerResponse -Get a unique name for a set of request options, to determine whether a -connection can be reused. In the http agent, this returns -`host:port:localAddress`. In the https agent, the name includes the -CA, cert, ciphers, and other HTTPS/TLS-specific options that determine -socket reusability. +This object is created internally by a HTTP server--not by the user. It is +passed as the second parameter to the `'request'` event. +The response implements the [Writable Stream][] interface. This is an +[EventEmitter][] with the following events: -## http.globalAgent +### Event: 'close' -Global instance of Agent which is used as the default for all http client -requests. +`function () { }` +Indicates that the underlying connection was terminated before +[response.end()][] was called or able to flush. -## Class: http.ClientRequest +### Event: 'finish' -This object is created internally and returned from `http.request()`. It -represents an _in-progress_ request whose header has already been queued. The -header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, -`removeHeader(name)` API. The actual header will be sent along with the first -data chunk or when closing the connection. +`function () { }` -To get the response, add a listener for `'response'` to the request object. -`'response'` will be emitted from the request object when the response -headers have been received. The `'response'` event is executed with one -argument which is an instance of [http.IncomingMessage][]. +Emitted when the response has been sent. More specifically, this event is +emitted when the last segment of the response headers and body have been +handed off to the operating system for transmission over the network. It +does not imply that the client has received anything yet. -During the `'response'` event, one can add listeners to the -response object; particularly to listen for the `'data'` event. +After this event, no more events will be emitted on the response object. -If no `'response'` handler is added, then the response will be -entirely discarded. However, if you add a `'response'` event handler, -then you **must** consume the data from the response object, either by -calling `response.read()` whenever there is a `'readable'` event, or -by adding a `'data'` handler, or by calling the `.resume()` method. -Until the data is consumed, the `'end'` event will not fire. Also, until -the data is read it will consume memory that can eventually lead to a -'process out of memory' error. +### response.addTrailers(headers) -Note: Node.js does not check whether Content-Length and the length of the body -which has been transmitted are equal or not. +This method adds HTTP trailing headers (a header but at the end of the +message) to the response. -The request implements the [Writable Stream][] interface. This is an -[EventEmitter][] with the following events: +Trailers will **only** be emitted if chunked encoding is used for the +response; if it is not (e.g., if the request was HTTP/1.0), they will +be silently discarded. -### Event: 'response' +Note that HTTP requires the `Trailer` header to be sent if you intend to +emit trailers, with a list of the header fields in its value. E.g., -`function (response) { }` + response.writeHead(200, { 'Content-Type': 'text/plain', + 'Trailer': 'Content-MD5' }); + response.write(fileData); + response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"}); + response.end(); -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][]. +Attempting to set a trailer field name that contains invalid characters will +result in a `TypeError` being thrown. -Options: +### response.end([data][, encoding][, callback]) -- `host`: A domain name or IP address of the server to issue the request to. -- `port`: Port of remote server. -- `socketPath`: Unix Domain Socket (use one of host:port or socketPath) +This method signals to the server that all of the response headers and body +have been sent; that server should consider this message complete. +The method, `response.end()`, MUST be called on each +response. -### Event: 'socket' +If `data` is specified, it is equivalent to calling +`response.write(data, encoding)` followed by `response.end(callback)`. -`function (socket) { }` +If `callback` is specified, it will be called when the response stream +is finished. -Emitted after a socket is assigned to this request. +### response.finished -### Event: 'connect' +Boolean value that indicates whether the response has completed. Starts +as `false`. After `response.end()` executes, the value will be `true`. -`function (response, socket, head) { }` +### response.getHeader(name) -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 -their connections closed. +Reads out a header that's already been queued but not sent to the client. Note +that the name is case insensitive. This can only be called before headers get +implicitly flushed. -A client server pair that show you how to listen for the `connect` event. +Example: - var http = require('http'); - var net = require('net'); - var url = require('url'); + var contentType = response.getHeader('content-type'); - // Create an HTTP tunneling proxy - var proxy = http.createServer(function (req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('okay'); - }); - proxy.on('connect', function(req, cltSocket, head) { - // connect to an origin server - var srvUrl = url.parse('http://' + req.url); - var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() { - cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + - 'Proxy-agent: Node.js-Proxy\r\n' + - '\r\n'); - srvSocket.write(head); - srvSocket.pipe(cltSocket); - cltSocket.pipe(srvSocket); - }); - }); +### response.headersSent - // now that proxy is running - proxy.listen(1337, '127.0.0.1', function() { +Boolean (read-only). True if headers were sent, false otherwise. - // make a request to a tunneling proxy - var options = { - port: 1337, - hostname: '127.0.0.1', - method: 'CONNECT', - path: 'www.google.com:80' - }; +### response.removeHeader(name) - var req = http.request(options); - req.end(); +Removes a header that's queued for implicit sending. - req.on('connect', function(res, socket, head) { - console.log('got connected!'); +Example: - // make a request over an HTTP tunnel - socket.write('GET / HTTP/1.1\r\n' + - 'Host: www.google.com:80\r\n' + - 'Connection: close\r\n' + - '\r\n'); - socket.on('data', function(chunk) { - console.log(chunk.toString()); - }); - socket.on('end', function() { - proxy.close(); - }); - }); - }); + response.removeHeader("Content-Encoding"); -### Event: 'upgrade' +### response.sendDate -`function (response, socket, head) { }` +When true, the Date header will be automatically generated and sent in +the response if it is not already present in the headers. Defaults to true. -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 -their connections closed. +This should only be disabled for testing; HTTP requires the Date header +in responses. -A client server pair that show you how to listen for the `upgrade` event. +### response.setHeader(name, value) - var http = require('http'); +Sets a single header value for implicit headers. If this header already exists +in the to-be-sent headers, its value will be replaced. Use an array of strings +here if you need to send multiple headers with the same name. - // Create an HTTP server - var srv = http.createServer(function (req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('okay'); - }); - srv.on('upgrade', function(req, socket, head) { - socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + - 'Upgrade: WebSocket\r\n' + - 'Connection: Upgrade\r\n' + - '\r\n'); +Example: - socket.pipe(socket); // echo back - }); + response.setHeader("Content-Type", "text/html"); - // now that server is running - srv.listen(1337, '127.0.0.1', function() { +or - // make a request - var options = { - port: 1337, - hostname: '127.0.0.1', - headers: { - 'Connection': 'Upgrade', - 'Upgrade': 'websocket' - } - }; + response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]); - var req = http.request(options); - req.end(); +Attempting to set a header field name that contains invalid characters will +result in a `TypeError` being thrown. - req.on('upgrade', function(res, socket, upgradeHead) { - console.log('got upgraded!'); - socket.end(); - process.exit(0); - }); - }); +### response.setTimeout(msecs, callback) -### Event: 'continue' +* `msecs` {Number} +* `callback` {Function} -`function () { }` +Sets the Socket's timeout value to `msecs`. If a callback is +provided, then it is added as a listener on the `'timeout'` event on +the response object. -Emitted when the server sends a '100 Continue' HTTP response, usually because -the request contained 'Expect: 100-continue'. This is an instruction that -the client should send the request body. +If no `'timeout'` listener is added to the request, the response, or +the server, then sockets are destroyed when they time out. If you +assign a handler on the request, the response, or the server's +`'timeout'` events, then it is your responsibility to handle timed out +sockets. -### Event: 'abort' +Returns `response`. -`function () { }` +### response.statusCode -Emitted when the request has been aborted by the client. This event is only -emitted on the first call to `abort()`. +When using implicit headers (not calling [response.writeHead()][] explicitly), +this property controls the status code that will be sent to the client when +the headers get flushed. -### request.flushHeaders() +Example: -Flush the request headers. + response.statusCode = 404; -For efficiency reasons, Node.js normally buffers the request headers until you -call `request.end()` or write the first chunk of request data. It then tries -hard to pack the request headers and data into a single TCP packet. +After response header was sent to the client, this property indicates the +status code which was sent out. -That's usually what you want (it saves a TCP round-trip) but not when the first -data isn't sent until possibly much later. `request.flushHeaders()` lets you bypass -the optimization and kickstart the request. +### response.statusMessage -### request.write(chunk[, encoding][, callback]) +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 +flushed. If this is left as `undefined` then the standard message for the status +code will be used. -Sends a chunk of the body. By calling this method -many times, the user can stream a request body to a -server--in that case it is suggested to use the -`['Transfer-Encoding', 'chunked']` header line when -creating the request. +Example: -The `chunk` argument should be a [Buffer][] or a string. + response.statusMessage = 'Not found'; -The `encoding` argument is optional and only applies when `chunk` is a string. -Defaults to `'utf8'`. +After response header was sent to the client, this property indicates the +status message which was sent out. -The `callback` argument is optional and will be called when this chunk of data -is flushed. +### response.write(chunk[, encoding][, callback]) -### request.end([data][, encoding][, callback]) +If this method is called and [response.writeHead()][] has not been called, +it will switch to implicit header mode and flush the implicit headers. -Finishes sending the request. If any parts of the body are -unsent, it will flush them to the stream. If the request is -chunked, this will send the terminating `'0\r\n\r\n'`. +This sends a chunk of the response body. This method may +be called multiple times to provide successive parts of the body. + +`chunk` can be a string or a buffer. If `chunk` is a string, +the second parameter specifies how to encode it into a byte stream. +By default the `encoding` is `'utf8'`. The last parameter `callback` +will be called when this chunk of data is flushed. -If `data` is specified, it is equivalent to calling -`request.write(data, encoding)` followed by `request.end(callback)`. +**Note**: This is the raw HTTP body and has nothing to do with +higher-level multi-part body encodings that may be used. -If `callback` is specified, it will be called when the request stream -is finished. +The first time `response.write()` is called, it will send the buffered +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 +data, and sends that separately. That is, the response is buffered up to the +first chunk of body. -### request.abort() +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. +`'drain'` will be emitted when the buffer is free again. -Marks the request as aborting. Calling this will cause remaining data -in the response to be dropped and the socket to be destroyed. +### response.writeContinue() -### request.setTimeout(timeout[, callback]) +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`. -Once a socket is assigned to this request and is connected -[socket.setTimeout()][] will be called. +### response.writeHead(statusCode[, statusMessage][, headers]) -Returns `request`. +Sends a response header to the request. The status code is a 3-digit HTTP +status code, like `404`. The last argument, `headers`, are the response headers. +Optionally one can give a human-readable `statusMessage` as the second +argument. -### request.setNoDelay([noDelay]) +Example: -Once a socket is assigned to this request and is connected -[socket.setNoDelay()][] will be called. + var body = 'hello world'; + response.writeHead(200, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' }); -### request.setSocketKeepAlive([enable][, initialDelay]) +This method must only be called once on a message and it must +be called before [response.end()][] is called. -Once a socket is assigned to this request and is connected -[socket.setKeepAlive()][] will be called. +If you call [response.write()][] or [response.end()][] before calling this, the +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 +works because the string `'hello world'` contains only single byte characters. +If the body contains higher coded characters then `Buffer.byteLength()` +should be used to determine the number of bytes in a given encoding. +And Node.js does not check whether Content-Length and the length of the body +which has been transmitted are equal or not. ## http.IncomingMessage @@ -961,15 +802,6 @@ following additional events, methods, and properties. Indicates that the underlying connection was closed. Just like `'end'`, this event occurs only once per response. -### message.httpVersion - -In case of server request, the HTTP version sent by the client. In the case of -client response, the HTTP version of the connected-to server. -Probably either `'1.1'` or `'1.0'`. - -Also `response.httpVersionMajor` is the first integer and -`response.httpVersionMinor` is the second. - ### message.headers The request/response headers object. @@ -984,6 +816,22 @@ Example: // accept: '*/*' } console.log(request.headers); +### message.httpVersion + +In case of server request, the HTTP version sent by the client. In the case of +client response, the HTTP version of the connected-to server. +Probably either `'1.1'` or `'1.0'`. + +Also `response.httpVersionMajor` is the first integer and +`response.httpVersionMinor` is the second. + +### message.method + +**Only valid for request obtained from [http.Server][].** + +The request method as a string. Read only. Example: +`'GET'`, `'DELETE'`. + ### message.rawHeaders The raw request/response headers list exactly as they were received. @@ -1006,10 +854,6 @@ Header names are not lowercased, and duplicates are not merged. // '*/*' ] console.log(request.rawHeaders); -### message.trailers - -The request/response trailers object. Only populated at the 'end' event. - ### message.rawTrailers The raw request/response trailer keys and values exactly as they were @@ -1024,12 +868,28 @@ Calls `message.connection.setTimeout(msecs, callback)`. Returns `message`. -### message.method +### message.statusCode -**Only valid for request obtained from [http.Server][].** +**Only valid for response obtained from `http.ClientRequest`.** -The request method as a string. Read only. Example: -`'GET'`, `'DELETE'`. +The 3-digit HTTP response status code. E.G. `404`. + +### message.statusMessage + +**Only valid for response obtained from `http.ClientRequest`.** + +### message.socket + +The `net.Socket` object associated with the connection. + +With HTTPS support, use [request.socket.getPeerCertificate()][] to obtain the +client's authentication details. + +The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + +### message.trailers + +The request/response trailers object. Only populated at the 'end' event. ### message.url @@ -1065,25 +925,155 @@ you can use the `require('querystring').parse` function, or pass query: { name: 'ryan' }, pathname: '/status' } -### message.statusCode +## http.METHODS -**Only valid for response obtained from `http.ClientRequest`.** +* {Array} -The 3-digit HTTP response status code. E.G. `404`. +A list of the HTTP methods that are supported by the parser. -### message.statusMessage +## http.STATUS_CODES -**Only valid for response obtained from `http.ClientRequest`.** +* {Object} -The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. +A collection of all the standard HTTP response status codes, and the +short description of each. For example, `http.STATUS_CODES[404] === 'Not +Found'`. -### message.socket +## http.createClient([port][, host]) -The `net.Socket` object associated with the connection. + Stability: 0 - Deprecated: Use [http.request][] instead. -With HTTPS support, use [request.socket.getPeerCertificate()][] to obtain the -client's authentication details. +Constructs a new HTTP client. `port` and `host` refer to the server to be +connected to. +## http.createServer([requestListener]) + +Returns a new instance of [http.Server](#http_class_http_server). + +The `requestListener` is a function which is automatically +added to the `'request'` event. + +## http.get(options[, callback]) + +Since most requests are GET requests without bodies, Node.js provides this +convenience method. The only difference between this method and `http.request()` +is that it sets the method to GET and calls `req.end()` automatically. + +Example: + + http.get("http://www.google.com/index.html", function(res) { + console.log("Got response: " + res.statusCode); + }).on('error', function(e) { + console.log("Got error: " + e.message); + }); + +## http.globalAgent + +Global instance of Agent which is used as the default for all http client +requests. + +## http.request(options[, callback]) + +Node.js maintains several connections per server to make HTTP requests. +This function allows one to transparently issue requests. + +`options` can be an object or a string. If `options` is a string, it is +automatically parsed with [url.parse()][]. + +Options: + +- `protocol`: Protocol to use. Defaults to `'http'`. +- `host`: A domain name or IP address of the server to issue the request to. + Defaults to `'localhost'`. +- `hostname`: Alias for `host`. To support `url.parse()` `hostname` is + preferred over `host`. +- `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 + used. +- `port`: Port of remote server. Defaults to 80. +- `localAddress`: Local interface to bind for network connections. +- `socketPath`: Unix Domain Socket (use one of host:port or socketPath). +- `method`: A string specifying the HTTP request method. Defaults to `'GET'`. +- `path`: Request path. Defaults to `'/'`. Should include query string if any. + E.G. `'/index.html?page=12'`. An exception is thrown when the request path + contains illegal characters. Currently, only spaces are rejected but that + may change in the future. +- `headers`: An object containing request headers. +- `auth`: Basic authentication i.e. `'user:password'` to compute an + Authorization header. +- `agent`: Controls [Agent][] behavior. When an Agent is used request will + default to `Connection: keep-alive`. Possible values: + - `undefined` (default): use [globalAgent][] for this host and port. + - `Agent` object: explicitly use the passed in `Agent`. + - `false`: opts out of connection pooling with an Agent, defaults request to + `Connection: close`. + +The optional `callback` parameter will be added as a one time listener for +the ['response'][] event. + +`http.request()` returns an instance of the [http.ClientRequest][] +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. + +Example: + + var postData = querystring.stringify({ + 'msg' : 'Hello World!' + }); + + var options = { + hostname: 'www.google.com', + port: 80, + path: '/upload', + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Length': postData.length + } + }; + + var req = http.request(options, function(res) { + console.log('STATUS: ' + res.statusCode); + console.log('HEADERS: ' + JSON.stringify(res.headers)); + res.setEncoding('utf8'); + res.on('data', function (chunk) { + console.log('BODY: ' + chunk); + }); + res.on('end', function() { + console.log('No more data in response.') + }) + }); + + req.on('error', function(e) { + console.log('problem with request: ' + e.message); + }); + + // write data to request body + req.write(postData); + req.end(); + +Note that in the example `req.end()` was called. With `http.request()` one +must always call `req.end()` to signify that you're done with the request - +even if there is no data being written to the request body. + +If any error is encountered during the request (be that with DNS resolution, +TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted +on the returned request object. + +There are a few special headers that should be noted. + +* Sending a 'Connection: keep-alive' will notify Node.js that the connection to + the server should be persisted until the next request. + +* Sending a 'Content-length' header will disable the default chunked encoding. + +* Sending an 'Expect' header will immediately send the request headers. + 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 + information. + +* Sending an Authorization header will override using the `auth` option + to compute basic authentication. ['checkContinue']: #http_event_checkcontinue ['listening']: net.html#net_event_listening From bed67d2e67776e133594fa85b464acc9dd37763e Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Wed, 4 Nov 2015 17:59:28 -0500 Subject: [PATCH 26/32] doc: sort https alphabetically Reorders, with no contextual changes, the https documentation alphabetically. --- doc/api/https.markdown | 101 ++++++++++++++++++++--------------------- 1 file changed, 49 insertions(+), 52 deletions(-) diff --git a/doc/api/https.markdown b/doc/api/https.markdown index 05617e0429adcf..1c3af5557b0072 100644 --- a/doc/api/https.markdown +++ b/doc/api/https.markdown @@ -5,6 +5,11 @@ HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a separate module. +## Class: https.Agent + +An Agent object for HTTPS similar to [http.Agent][]. See [https.request()][] +for more information. + ## Class: https.Server This class is a subclass of `tls.Server` and emits events same as @@ -54,16 +59,56 @@ Or res.end("hello world\n"); }).listen(8000); +### server.close([callback]) + +See [http.close()][] for details. -### server.listen(port[, host][, backlog][, callback]) -### server.listen(path[, callback]) ### server.listen(handle[, callback]) +### server.listen(path[, callback]) +### server.listen(port[, host][, backlog][, callback]) See [http.listen()][] for details. -### server.close([callback]) +## https.get(options, callback) -See [http.close()][] for details. +Like `http.get()` but for HTTPS. + +`options` can be an object or a string. If `options` is a string, it is +automatically parsed with [url.parse()](url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost). + +Example: + + var https = require('https'); + + https.get('https://encrypted.google.com/', function(res) { + console.log("statusCode: ", res.statusCode); + console.log("headers: ", res.headers); + + res.on('data', function(d) { + process.stdout.write(d); + }); + + }).on('error', function(e) { + console.error(e); + }); + +## https.globalAgent + +Global instance of [https.Agent][] for all HTTPS client requests. + +[http.Server#setTimeout()]: http.html#http_server_settimeout_msecs_callback +[http.Server#timeout]: http.html#http_server_timeout +[Agent]: #https_class_https_agent +[globalAgent]: #https_https_globalagent +[http.listen()]: http.html#http_server_listen_port_hostname_backlog_callback +[http.close()]: http.html#http_server_close_callback +[http.Agent]: http.html#http_class_http_agent +[http.request()]: http.html#http_http_request_options_callback +[https.Agent]: #https_class_https_agent +[https.request()]: #https_https_request_options_callback +[tls.connect()]: tls.html#tls_tls_connect_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 ## https.request(options, callback) @@ -181,51 +226,3 @@ Example: var req = https.request(options, function(res) { ... } - -## https.get(options, callback) - -Like `http.get()` but for HTTPS. - -`options` can be an object or a string. If `options` is a string, it is -automatically parsed with [url.parse()](url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost). - -Example: - - var https = require('https'); - - https.get('https://encrypted.google.com/', function(res) { - console.log("statusCode: ", res.statusCode); - console.log("headers: ", res.headers); - - res.on('data', function(d) { - process.stdout.write(d); - }); - - }).on('error', function(e) { - console.error(e); - }); - - -## Class: https.Agent - -An Agent object for HTTPS similar to [http.Agent][]. See [https.request()][] -for more information. - - -## https.globalAgent - -Global instance of [https.Agent][] for all HTTPS client requests. - -[http.Server#setTimeout()]: http.html#http_server_settimeout_msecs_callback -[http.Server#timeout]: http.html#http_server_timeout -[Agent]: #https_class_https_agent -[globalAgent]: #https_https_globalagent -[http.listen()]: http.html#http_server_listen_port_hostname_backlog_callback -[http.close()]: http.html#http_server_close_callback -[http.Agent]: http.html#http_class_http_agent -[http.request()]: http.html#http_http_request_options_callback -[https.Agent]: #https_class_https_agent -[https.request()]: #https_https_request_options_callback -[tls.connect()]: tls.html#tls_tls_connect_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 From 5b09a1c3ac80c16b78c3ec78d065b902cfa0e645 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Thu, 5 Nov 2015 10:28:34 -0500 Subject: [PATCH 27/32] doc: sort util alphabetically Reorders, with no contextual changes, the util documentation alphabetically. --- doc/api/util.markdown | 344 +++++++++++++++++++++--------------------- 1 file changed, 171 insertions(+), 173 deletions(-) diff --git a/doc/api/util.markdown b/doc/api/util.markdown index 9914deb48050db..df81b591fdee09 100644 --- a/doc/api/util.markdown +++ b/doc/api/util.markdown @@ -12,6 +12,12 @@ purposes, however, you are encouraged to write your own utilities. We are not interested in any future additions to the `util` module that are unnecessary for node.js's internal functionality. +## util.debug(string) + + Stability: 0 - Deprecated: use console.error() instead. + +Deprecated predecessor of `console.error`. + ## util.debuglog(section) * `section` {String} The section of the program to be debugged @@ -43,6 +49,40 @@ environment variable set, then it will not print anything. You may separate multiple `NODE_DEBUG` environment variables with a comma. For example, `NODE_DEBUG=fs,net,tls`. +## util.deprecate(function, string) + +Marks that a method should not be used any more. + + var util = require('util'); + + exports.puts = util.deprecate(function() { + for (var i = 0, len = arguments.length; i < len; ++i) { + process.stdout.write(arguments[i] + '\n'); + } + }, 'util.puts: Use console.log instead'); + +It returns a modified function which warns once by default. + +If `--no-deprecation` is set then this function is a NO-OP. Configurable +at run-time through the `process.noDeprecation` boolean (only effective +when set before a module is loaded.) + +If `--trace-deprecation` is set, a warning and a stack trace are logged +to the console the first time the deprecated API is used. Configurable +at run-time through the `process.traceDeprecation` boolean. + +If `--throw-deprecation` is set then the application throws an exception +when the deprecated API is used. Configurable at run-time through the +`process.throwDeprecation` boolean. + +`process.throwDeprecation` takes precedence over `process.traceDeprecation`. + +## util.error([...]) + + Stability: 0 - Deprecated: Use console.error() instead. + +Deprecated predecessor of `console.error`. + ## util.format(format[, ...]) Returns a formatted string using the first argument as a `printf`-like format. @@ -74,12 +114,38 @@ Each argument is converted to a string with `util.inspect()`. util.format(1, 2, 3); // '1 2 3' +## util.inherits(constructor, superConstructor) -## util.log(string) +Inherit the prototype methods from one +[constructor](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor) +into another. The prototype of `constructor` will be set to a new +object created from `superConstructor`. -Output with timestamp on `stdout`. +As an additional convenience, `superConstructor` will be accessible +through the `constructor.super_` property. - require('util').log('Timestamped message.'); + var util = require("util"); + var EventEmitter = require("events"); + + function MyStream() { + EventEmitter.call(this); + } + + util.inherits(MyStream, EventEmitter); + + MyStream.prototype.write = function(data) { + this.emit("data", data); + } + + var stream = new MyStream(); + + console.log(stream instanceof EventEmitter); // true + console.log(MyStream.super_ === EventEmitter); // true + + stream.on("data", function(data) { + console.log('Received data: "' + data + '"'); + }) + stream.write("It works!"); // Received data: "It works!" ## util.inspect(object[, options]) @@ -111,30 +177,6 @@ Values may supply their own custom `inspect(depth, opts)` functions, when called they receive the current depth in the recursive inspection, as well as the options object passed to `util.inspect()`. -### Customizing `util.inspect` colors - - - -Color output (if enabled) of `util.inspect` is customizable globally -via `util.inspect.styles` and `util.inspect.colors` objects. - -`util.inspect.styles` is a map assigning each style a color -from `util.inspect.colors`. -Highlighted styles and their default values are: - * `number` (yellow) - * `boolean` (yellow) - * `string` (green) - * `date` (magenta) - * `regexp` (red) - * `null` (bold) - * `undefined` (grey) - * `special` - only function at this time (cyan) - * `name` (intentionally no styling) - -Predefined color codes are: `white`, `grey`, `black`, `blue`, `cyan`, -`green`, `magenta`, `red` and `yellow`. -There are also `bold`, `italic`, `underline` and `inverse` codes. - ### Custom `inspect()` function on Objects @@ -164,6 +206,30 @@ formatted according to the returned Object. This is similar to how util.inspect(obj); // "{ bar: 'baz' }" +### Customizing `util.inspect` colors + + + +Color output (if enabled) of `util.inspect` is customizable globally +via `util.inspect.styles` and `util.inspect.colors` objects. + +`util.inspect.styles` is a map assigning each style a color +from `util.inspect.colors`. +Highlighted styles and their default values are: + * `number` (yellow) + * `boolean` (yellow) + * `string` (green) + * `date` (magenta) + * `regexp` (red) + * `null` (bold) + * `undefined` (grey) + * `special` - only function at this time (cyan) + * `name` (intentionally no styling) + +Predefined color codes are: `white`, `grey`, `black`, `blue`, `cyan`, +`green`, `magenta`, `red` and `yellow`. +There are also `bold`, `italic`, `underline` and `inverse` codes. + ## util.isArray(object) @@ -182,20 +248,35 @@ Returns `true` if the given "object" is an `Array`. `false` otherwise. util.isArray({}) // false -## util.isRegExp(object) +## util.isBoolean(object) Stability: 0 - Deprecated -Returns `true` if the given "object" is a `RegExp`. `false` otherwise. +Returns `true` if the given "object" is a `Boolean`. `false` otherwise. var util = require('util'); - util.isRegExp(/some regexp/) - // true - util.isRegExp(new RegExp('another regexp')) + util.isBoolean(1) + // false + util.isBoolean(0) + // false + util.isBoolean(false) // true - util.isRegExp({}) + +## util.isBuffer(object) + + Stability: 0 - Deprecated + +Returns `true` if the given "object" is a `Buffer`. `false` otherwise. + + var util = require('util'); + + util.isBuffer({ length: 0 }) // false + util.isBuffer([]) + // false + util.isBuffer(new Buffer('hello world')) + // true ## util.isDate(object) @@ -227,19 +308,22 @@ Returns `true` if the given "object" is an `Error`. `false` otherwise. util.isError({ name: 'Error', message: 'an error occurred' }) // false -## util.isBoolean(object) +## util.isFunction(object) Stability: 0 - Deprecated -Returns `true` if the given "object" is a `Boolean`. `false` otherwise. +Returns `true` if the given "object" is a `Function`. `false` otherwise. var util = require('util'); - util.isBoolean(1) - // false - util.isBoolean(0) + function Foo() {} + var Bar = function() {}; + + util.isFunction({}) // false - util.isBoolean(false) + util.isFunction(Foo) + // true + util.isFunction(Bar) // true ## util.isNull(object) @@ -289,54 +373,6 @@ Returns `true` if the given "object" is a `Number`. `false` otherwise. util.isNumber(NaN) // true -## util.isString(object) - - Stability: 0 - Deprecated - -Returns `true` if the given "object" is a `String`. `false` otherwise. - - var util = require('util'); - - util.isString('') - // true - util.isString('foo') - // true - util.isString(String('foo')) - // true - util.isString(5) - // false - -## util.isSymbol(object) - - Stability: 0 - Deprecated - -Returns `true` if the given "object" is a `Symbol`. `false` otherwise. - - var util = require('util'); - - util.isSymbol(5) - // false - util.isSymbol('foo') - // false - util.isSymbol(Symbol('foo')) - // true - -## util.isUndefined(object) - - Stability: 0 - Deprecated - -Returns `true` if the given "object" is `undefined`. `false` otherwise. - - var util = require('util'); - - var foo; - util.isUndefined(5) - // false - util.isUndefined(foo) - // true - util.isUndefined(null) - // false - ## util.isObject(object) Stability: 0 - Deprecated @@ -355,24 +391,6 @@ Returns `true` if the given "object" is strictly an `Object` __and__ not a util.isObject(function(){}) // false -## util.isFunction(object) - - Stability: 0 - Deprecated - -Returns `true` if the given "object" is a `Function`. `false` otherwise. - - var util = require('util'); - - function Foo() {} - var Bar = function() {}; - - util.isFunction({}) - // false - util.isFunction(Foo) - // true - util.isFunction(Bar) - // true - ## util.isPrimitive(object) Stability: 0 - Deprecated @@ -400,100 +418,74 @@ Returns `true` if the given "object" is a primitive type. `false` otherwise. util.isPrimitive(new Date()) // false -## util.isBuffer(object) +## util.isRegExp(object) Stability: 0 - Deprecated -Returns `true` if the given "object" is a `Buffer`. `false` otherwise. +Returns `true` if the given "object" is a `RegExp`. `false` otherwise. var util = require('util'); - util.isBuffer({ length: 0 }) - // false - util.isBuffer([]) - // false - util.isBuffer(new Buffer('hello world')) + util.isRegExp(/some regexp/) // true + util.isRegExp(new RegExp('another regexp')) + // true + util.isRegExp({}) + // false -## util.inherits(constructor, superConstructor) - -Inherit the prototype methods from one -[constructor](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor) -into another. The prototype of `constructor` will be set to a new -object created from `superConstructor`. - -As an additional convenience, `superConstructor` will be accessible -through the `constructor.super_` property. - - var util = require("util"); - var EventEmitter = require("events"); - - function MyStream() { - EventEmitter.call(this); - } - - util.inherits(MyStream, EventEmitter); - - MyStream.prototype.write = function(data) { - this.emit("data", data); - } - - var stream = new MyStream(); - - console.log(stream instanceof EventEmitter); // true - console.log(MyStream.super_ === EventEmitter); // true - - stream.on("data", function(data) { - console.log('Received data: "' + data + '"'); - }) - stream.write("It works!"); // Received data: "It works!" - +## util.isString(object) -## util.deprecate(function, string) + Stability: 0 - Deprecated -Marks that a method should not be used any more. +Returns `true` if the given "object" is a `String`. `false` otherwise. var util = require('util'); - exports.puts = util.deprecate(function() { - for (var i = 0, len = arguments.length; i < len; ++i) { - process.stdout.write(arguments[i] + '\n'); - } - }, 'util.puts: Use console.log instead'); - -It returns a modified function which warns once by default. + util.isString('') + // true + util.isString('foo') + // true + util.isString(String('foo')) + // true + util.isString(5) + // false -If `--no-deprecation` is set then this function is a NO-OP. Configurable -at run-time through the `process.noDeprecation` boolean (only effective -when set before a module is loaded.) +## util.isSymbol(object) -If `--trace-deprecation` is set, a warning and a stack trace are logged -to the console the first time the deprecated API is used. Configurable -at run-time through the `process.traceDeprecation` boolean. + Stability: 0 - Deprecated -If `--throw-deprecation` is set then the application throws an exception -when the deprecated API is used. Configurable at run-time through the -`process.throwDeprecation` boolean. +Returns `true` if the given "object" is a `Symbol`. `false` otherwise. -`process.throwDeprecation` takes precedence over `process.traceDeprecation`. + var util = require('util'); -## util.debug(string) + util.isSymbol(5) + // false + util.isSymbol('foo') + // false + util.isSymbol(Symbol('foo')) + // true - Stability: 0 - Deprecated: use console.error() instead. +## util.isUndefined(object) -Deprecated predecessor of `console.error`. + Stability: 0 - Deprecated -## util.error([...]) +Returns `true` if the given "object" is `undefined`. `false` otherwise. - Stability: 0 - Deprecated: Use console.error() instead. + var util = require('util'); -Deprecated predecessor of `console.error`. + var foo; + util.isUndefined(5) + // false + util.isUndefined(foo) + // true + util.isUndefined(null) + // false -## util.puts([...]) +## util.log(string) - Stability: 0 - Deprecated: Use console.log() instead. +Output with timestamp on `stdout`. -Deprecated predecessor of `console.log`. + require('util').log('Timestamped message.'); ## util.print([...]) @@ -507,3 +499,9 @@ Deprecated predecessor of `console.log`. Stability: 0 - Deprecated: Use readableStream.pipe(writableStream) Deprecated predecessor of `stream.pipe()`. + +## util.puts([...]) + + Stability: 0 - Deprecated: Use console.log() instead. + +Deprecated predecessor of `console.log`. From 37d037be8e397e6144d5393330d62d536e3aeba5 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Thu, 5 Nov 2015 10:40:47 -0500 Subject: [PATCH 28/32] doc: sort zlib alphabetically Reorders, with some contextual changes, the zlib documentation alphabetically. - Put Convenience Methods children under the Convenience Methods header - Renamed Options to Class Options and put above the Class definitions --- doc/api/zlib.markdown | 311 +++++++++++++++++++++--------------------- 1 file changed, 158 insertions(+), 153 deletions(-) diff --git a/doc/api/zlib.markdown b/doc/api/zlib.markdown index 8ca7fbad2253e3..08f8fbdf7719e1 100644 --- a/doc/api/zlib.markdown +++ b/doc/api/zlib.markdown @@ -103,159 +103,6 @@ tradeoffs involved in zlib usage. } }).listen(1337); -## zlib.createGzip([options]) - -Returns a new [Gzip](#zlib_class_zlib_gzip) object with an -[options](#zlib_options). - -## zlib.createGunzip([options]) - -Returns a new [Gunzip](#zlib_class_zlib_gunzip) object with an -[options](#zlib_options). - -## zlib.createDeflate([options]) - -Returns a new [Deflate](#zlib_class_zlib_deflate) object with an -[options](#zlib_options). - -## zlib.createInflate([options]) - -Returns a new [Inflate](#zlib_class_zlib_inflate) object with an -[options](#zlib_options). - -## zlib.createDeflateRaw([options]) - -Returns a new [DeflateRaw](#zlib_class_zlib_deflateraw) object with an -[options](#zlib_options). - -## zlib.createInflateRaw([options]) - -Returns a new [InflateRaw](#zlib_class_zlib_inflateraw) object with an -[options](#zlib_options). - -## zlib.createUnzip([options]) - -Returns a new [Unzip](#zlib_class_zlib_unzip) object with an -[options](#zlib_options). - - -## Class: zlib.Zlib - -Not exported by the `zlib` module. It is documented here because it is the base -class of the compressor/decompressor classes. - -### zlib.flush([kind], callback) - -`kind` defaults to `zlib.Z_FULL_FLUSH`. - -Flush pending data. Don't call this frivolously, premature flushes negatively -impact the effectiveness of the compression algorithm. - -### zlib.params(level, strategy, callback) - -Dynamically update the compression level and compression strategy. -Only applicable to deflate algorithm. - -### zlib.reset() - -Reset the compressor/decompressor to factory defaults. Only applicable to -the inflate and deflate algorithms. - -## Class: zlib.Gzip - -Compress data using gzip. - -## Class: zlib.Gunzip - -Decompress a gzip stream. - -## Class: zlib.Deflate - -Compress data using deflate. - -## Class: zlib.Inflate - -Decompress a deflate stream. - -## Class: zlib.DeflateRaw - -Compress data using deflate, and do not append a zlib header. - -## Class: zlib.InflateRaw - -Decompress a raw deflate stream. - -## Class: zlib.Unzip - -Decompress either a Gzip- or Deflate-compressed stream by auto-detecting -the header. - -## Convenience Methods - - - -All of these take a string or buffer as the first argument, an optional second -argument to supply options to the zlib classes and will call the supplied -callback with `callback(error, result)`. - -Every method has a `*Sync` counterpart, which accept the same arguments, but -without a callback. - -## zlib.deflate(buf[, options], callback) -## zlib.deflateSync(buf[, options]) - -Compress a string with Deflate. - -## zlib.deflateRaw(buf[, options], callback) -## zlib.deflateRawSync(buf[, options]) - -Compress a string with DeflateRaw. - -## zlib.gzip(buf[, options], callback) -## zlib.gzipSync(buf[, options]) - -Compress a string with Gzip. - -## zlib.gunzip(buf[, options], callback) -## zlib.gunzipSync(buf[, options]) - -Decompress a raw Buffer with Gunzip. - -## zlib.inflate(buf[, options], callback) -## zlib.inflateSync(buf[, options]) - -Decompress a raw Buffer with Inflate. - -## zlib.inflateRaw(buf[, options], callback) -## zlib.inflateRawSync(buf[, options]) - -Decompress a raw Buffer with InflateRaw. - -## zlib.unzip(buf[, options], callback) -## zlib.unzipSync(buf[, options]) - -Decompress a raw Buffer with Unzip. - -## Options - - - -Each class takes an options object. All options are optional. - -Note that some options are only relevant when compressing, and are -ignored by the decompression classes. - -* flush (default: `zlib.Z_NO_FLUSH`) -* chunkSize (default: 16*1024) -* windowBits -* level (compression only) -* memLevel (compression only) -* strategy (compression only) -* dictionary (deflate/inflate only, empty dictionary by default) - -See the description of `deflateInit2` and `inflateInit2` at - for more information on these. - ## Memory Usage Tuning @@ -361,3 +208,161 @@ The deflate compression method (the only one supported in this version). For initializing zalloc, zfree, opaque. * `zlib.Z_NULL` + +## Class Options + + + +Each class takes an options object. All options are optional. + +Note that some options are only relevant when compressing, and are +ignored by the decompression classes. + +* flush (default: `zlib.Z_NO_FLUSH`) +* chunkSize (default: 16*1024) +* windowBits +* level (compression only) +* memLevel (compression only) +* strategy (compression only) +* dictionary (deflate/inflate only, empty dictionary by default) + +See the description of `deflateInit2` and `inflateInit2` at + for more information on these. + +## Class: zlib.Deflate + +Compress data using deflate. + +## Class: zlib.DeflateRaw + +Compress data using deflate, and do not append a zlib header. + +## Class: zlib.Gunzip + +Decompress a gzip stream. + +## Class: zlib.Gzip + +Compress data using gzip. + +## Class: zlib.Inflate + +Decompress a deflate stream. + +## Class: zlib.InflateRaw + +Decompress a raw deflate stream. + +## Class: zlib.Unzip + +Decompress either a Gzip- or Deflate-compressed stream by auto-detecting +the header. + +## Class: zlib.Zlib + +Not exported by the `zlib` module. It is documented here because it is the base +class of the compressor/decompressor classes. + +### zlib.flush([kind], callback) + +`kind` defaults to `zlib.Z_FULL_FLUSH`. + +Flush pending data. Don't call this frivolously, premature flushes negatively +impact the effectiveness of the compression algorithm. + +### zlib.params(level, strategy, callback) + +Dynamically update the compression level and compression strategy. +Only applicable to deflate algorithm. + +### zlib.reset() + +Reset the compressor/decompressor to factory defaults. Only applicable to +the inflate and deflate algorithms. + +## zlib.createDeflate([options]) + +Returns a new [Deflate](#zlib_class_zlib_deflate) object with an +[options](#zlib_options). + +## zlib.createDeflateRaw([options]) + +Returns a new [DeflateRaw](#zlib_class_zlib_deflateraw) object with an +[options](#zlib_options). + +## zlib.createGunzip([options]) + +Returns a new [Gunzip](#zlib_class_zlib_gunzip) object with an +[options](#zlib_options). + +## zlib.createGzip([options]) + +Returns a new [Gzip](#zlib_class_zlib_gzip) object with an +[options](#zlib_options). + +## zlib.createInflate([options]) + +Returns a new [Inflate](#zlib_class_zlib_inflate) object with an +[options](#zlib_options). + +## zlib.createInflateRaw([options]) + +Returns a new [InflateRaw](#zlib_class_zlib_inflateraw) object with an +[options](#zlib_options). + +## zlib.createUnzip([options]) + +Returns a new [Unzip](#zlib_class_zlib_unzip) object with an +[options](#zlib_options). + +## Convenience Methods + + + +All of these take a string or buffer as the first argument, an optional second +argument to supply options to the zlib classes and will call the supplied +callback with `callback(error, result)`. + +Every method has a `*Sync` counterpart, which accept the same arguments, but +without a callback. + +### zlib.deflate(buf[, options], callback) + +Compress a string with Deflate. + +### zlib.deflateRaw(buf[, options], callback) +### zlib.deflateRawSync(buf[, options]) + +Compress a string with DeflateRaw. + +### zlib.deflateSync(buf[, options]) + +Compress a string with Deflate. + +### zlib.gunzip(buf[, options], callback) +### zlib.gunzipSync(buf[, options]) + +Decompress a raw Buffer with Gunzip. + +### zlib.gzip(buf[, options], callback) +### zlib.gzipSync(buf[, options]) + +Compress a string with Gzip. + +### zlib.inflate(buf[, options], callback) + +Decompress a raw Buffer with Inflate. + +### zlib.inflateRaw(buf[, options], callback) +### zlib.inflateRawSync(buf[, options]) + +Decompress a raw Buffer with InflateRaw. + +### zlib.inflateSync(buf[, options]) + +Decompress a raw Buffer with Inflate. + +### zlib.unzip(buf[, options], callback) +### zlib.unzipSync(buf[, options]) + +Decompress a raw Buffer with Unzip. From 8dbd518895c505eca92f3e7390b05ee167b2aee2 Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Thu, 5 Nov 2015 11:00:46 -0500 Subject: [PATCH 29/32] doc: sort process alphabetically Reorders, with no contextual changes, the process documentation alphabetically. --- doc/api/process.markdown | 933 +++++++++++++++++++-------------------- 1 file changed, 448 insertions(+), 485 deletions(-) diff --git a/doc/api/process.markdown b/doc/api/process.markdown index eecf494c48bf27..77dbafd9cb8a3a 100644 --- a/doc/api/process.markdown +++ b/doc/api/process.markdown @@ -5,50 +5,15 @@ The `process` object is a global object and can be accessed from anywhere. It is an instance of [EventEmitter][]. -## Exit Codes +## Event: 'beforeExit' -Node.js will normally exit with a `0` status code when no more async -operations are pending. The following status codes are used in other -cases: +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 +for 'beforeExit' can make asynchronous calls, and cause Node.js to continue. -* `1` **Uncaught Fatal Exception** - There was an uncaught exception, - and it was not handled by a domain or an `uncaughtException` event - handler. -* `2` - Unused (reserved by Bash for builtin misuse) -* `3` **Internal JavaScript Parse Error** - The JavaScript source code - internal in Node.js's bootstrapping process caused a parse error. This - is extremely rare, and generally can only happen during development - of Node.js itself. -* `4` **Internal JavaScript Evaluation Failure** - The JavaScript - source code internal in Node.js's bootstrapping process failed to - return a function value when evaluated. This is extremely rare, and - generally can only happen during development of Node.js itself. -* `5` **Fatal Error** - There was a fatal unrecoverable error in V8. - Typically a message will be printed to stderr with the prefix `FATAL - ERROR`. -* `6` **Non-function Internal Exception Handler** - There was an - uncaught exception, but the internal fatal exception handler - function was somehow set to a non-function, and could not be called. -* `7` **Internal Exception Handler Run-Time Failure** - There was an - uncaught exception, and the internal fatal exception handler - function itself threw an error while attempting to handle it. This - can happen, for example, if a `process.on('uncaughtException')` or - `domain.on('error')` handler throws an error. -* `8` - Unused. In previous versions of Node.js, exit code 8 sometimes - indicated an uncaught exception. -* `9` - **Invalid Argument** - Either an unknown option was specified, - or an option requiring a value was provided without a value. -* `10` **Internal JavaScript Run-Time Failure** - The JavaScript - source code internal in Node.js's bootstrapping process threw an error - when the bootstrapping function was called. This is extremely rare, - and generally can only happen during development of Node.js itself. -* `12` **Invalid Debug Argument** - The `--debug` and/or `--debug-brk` - options were set, but an invalid port number was chosen. -* `>128` **Signal Exits** - If Node.js receives a fatal signal such as - `SIGKILL` or `SIGHUP`, then its exit code will be `128` plus the - value of the signal code. This is a standard Unix practice, since - exit codes are defined to be 7-bit integers, and signal exits set - the high-order bit, and then contain the value of the signal code. +'beforeExit' is not emitted for conditions causing explicit termination, such as +`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. ## Event: 'exit' @@ -72,7 +37,6 @@ Example of listening for `exit`: console.log('About to exit with code:', code); }); - ## Event: 'message' * `message` {Object} a parsed JSON object or primitive value @@ -82,17 +46,44 @@ Example of listening for `exit`: Messages sent by [ChildProcess.send()][] are obtained using the `'message'` event on the child's process object. +## Event: 'rejectionHandled' -## Event: 'beforeExit' +Emitted whenever a Promise was rejected and an error handler was attached to it +(for example with `.catch()`) later than after an event loop turn. This event +is emitted with the following arguments: -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 -for 'beforeExit' can make asynchronous calls, and cause Node.js to continue. + - `p` the promise that was previously emitted in an `'unhandledRejection'` + event, but which has now gained a rejection handler. -'beforeExit' is not emitted for conditions causing explicit termination, such as -`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. +There is no notion of a top level for a promise chain at which rejections can +always be handled. Being inherently asynchronous in nature, a promise rejection +can be be handled at a future point in time — possibly much later than the +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 +an ever-growing list of unhandled exceptions, with promises there is a +growing-and-shrinking list of unhandled rejections. In synchronous code, the +'uncaughtException' event tells you when the list of unhandled exceptions +grows. And in asynchronous code, the `'unhandledRejection'` event tells you +when the list of unhandled rejections grows, while the 'rejectionHandled' +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 +the rejected promise reasons at a given time: + + var unhandledRejections = new Map(); + process.on('unhandledRejection', function(reason, p) { + unhandledRejections.set(p, reason); + }); + process.on('rejectionHandled', function(p) { + unhandledRejections.delete(p); + }); +This map will grow and shrink over time, reflecting rejections that start +unhandled and then become handled. You could record the errors in some error +log, either periodically (probably best for long-running programs, allowing +you to clear the map, which in the case of a very buggy program could grow +indefinitely) or upon process exit (more convenient for scripts). ## Event: 'uncaughtException' @@ -177,44 +168,50 @@ this, you can either attach a dummy `.catch(function() { })` handler to emitted, or you can use the `'rejectionHandled'` event. Below is an explanation of how to do that. -## Event: 'rejectionHandled' - -Emitted whenever a Promise was rejected and an error handler was attached to it -(for example with `.catch()`) later than after an event loop turn. This event -is emitted with the following arguments: - - - `p` the promise that was previously emitted in an `'unhandledRejection'` - event, but which has now gained a rejection handler. - -There is no notion of a top level for a promise chain at which rejections can -always be handled. Being inherently asynchronous in nature, a promise rejection -can be be handled at a future point in time — possibly much later than the -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 -an ever-growing list of unhandled exceptions, with promises there is a -growing-and-shrinking list of unhandled rejections. In synchronous code, the -'uncaughtException' event tells you when the list of unhandled exceptions -grows. And in asynchronous code, the `'unhandledRejection'` event tells you -when the list of unhandled rejections grows, while the 'rejectionHandled' -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 -the rejected promise reasons at a given time: +## Exit Codes - var unhandledRejections = new Map(); - process.on('unhandledRejection', function(reason, p) { - unhandledRejections.set(p, reason); - }); - process.on('rejectionHandled', function(p) { - unhandledRejections.delete(p); - }); +Node.js will normally exit with a `0` status code when no more async +operations are pending. The following status codes are used in other +cases: -This map will grow and shrink over time, reflecting rejections that start -unhandled and then become handled. You could record the errors in some error -log, either periodically (probably best for long-running programs, allowing -you to clear the map, which in the case of a very buggy program could grow -indefinitely) or upon process exit (more convenient for scripts). +* `1` **Uncaught Fatal Exception** - There was an uncaught exception, + and it was not handled by a domain or an `uncaughtException` event + handler. +* `2` - Unused (reserved by Bash for builtin misuse) +* `3` **Internal JavaScript Parse Error** - The JavaScript source code + internal in Node.js's bootstrapping process caused a parse error. This + is extremely rare, and generally can only happen during development + of Node.js itself. +* `4` **Internal JavaScript Evaluation Failure** - The JavaScript + source code internal in Node.js's bootstrapping process failed to + return a function value when evaluated. This is extremely rare, and + generally can only happen during development of Node.js itself. +* `5` **Fatal Error** - There was a fatal unrecoverable error in V8. + Typically a message will be printed to stderr with the prefix `FATAL + ERROR`. +* `6` **Non-function Internal Exception Handler** - There was an + uncaught exception, but the internal fatal exception handler + function was somehow set to a non-function, and could not be called. +* `7` **Internal Exception Handler Run-Time Failure** - There was an + uncaught exception, and the internal fatal exception handler + function itself threw an error while attempting to handle it. This + can happen, for example, if a `process.on('uncaughtException')` or + `domain.on('error')` handler throws an error. +* `8` - Unused. In previous versions of Node.js, exit code 8 sometimes + indicated an uncaught exception. +* `9` - **Invalid Argument** - Either an unknown option was specified, + or an option requiring a value was provided without a value. +* `10` **Internal JavaScript Run-Time Failure** - The JavaScript + source code internal in Node.js's bootstrapping process threw an error + when the bootstrapping function was called. This is extremely rare, + and generally can only happen during development of Node.js itself. +* `12` **Invalid Debug Argument** - The `--debug` and/or `--debug-brk` + options were set, but an invalid port number was chosen. +* `>128` **Signal Exits** - If Node.js receives a fatal signal such as + `SIGKILL` or `SIGHUP`, then its exit code will be `128` plus the + value of the signal code. This is a standard Unix practice, since + exit codes are defined to be 7-bit integers, and signal exits set + the high-order bit, and then contain the value of the signal code. ## Signal Events @@ -270,80 +267,16 @@ can be used to test for the existence of a process. Sending `SIGINT`, `SIGTERM`, and `SIGKILL` cause the unconditional termination of the target process. -## process.stdout - -A `Writable Stream` to `stdout` (on fd `1`). - -For example, a `console.log` equivalent could look like this: - - console.log = function(msg) { - process.stdout.write(msg + '\n'); - }; - -`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` -event and that writes are always blocking. - -To check if Node.js is being run in a TTY context, read the `isTTY` property -on `process.stderr`, `process.stdout`, or `process.stdin`: - - $ node -p "Boolean(process.stdin.isTTY)" - true - $ echo "foo" | node -p "Boolean(process.stdin.isTTY)" - false - - $ node -p "Boolean(process.stdout.isTTY)" - true - $ node -p "Boolean(process.stdout.isTTY)" | cat - false - -See [the tty docs](tty.html#tty_tty) for more information. - -## process.stderr - -A writable stream to stderr (on fd `2`). - -`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` -event and that writes are usually blocking. - -- They are blocking in the case that they refer to regular files or TTY file - descriptors. -- In the case they refer to pipes: - - They are blocking in Linux/Unix. - - They are non-blocking like other streams in Windows. - - -## process.stdin - -A `Readable Stream` for stdin (on fd `0`). - -Example of opening standard input and listening for both events: - - process.stdin.setEncoding('utf8'); - - process.stdin.on('readable', function() { - var chunk = process.stdin.read(); - if (chunk !== null) { - process.stdout.write('data: ' + chunk); - } - }); +## process.abort() - process.stdin.on('end', function() { - process.stdout.write('end'); - }); +This causes Node.js to emit an abort. This will cause Node.js to exit and +generate a core file. -As a Stream, `process.stdin` can also be used in "old" mode that is compatible -with scripts written for node.js prior to v0.10. -For more information see -[Stream compatibility](stream.html#stream_compatibility_with_older_node_js_versions). +## process.arch -In "old" Streams mode the stdin stream is paused by default, so one -must call `process.stdin.resume()` to read from it. Note also that calling -`process.stdin.resume()` itself would switch stream to "old" mode. +What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`. -If you are starting a new project you should prefer a more recent "new" Streams -mode over "old" one. + console.log('This processor architecture is ' + process.arch); ## process.argv @@ -365,64 +298,70 @@ This will generate: 3: two=three 4: four +## process.chdir(directory) -## process.execPath +Changes the current working directory of the process or throws an exception if that fails. -This is the absolute pathname of the executable that started the process. + console.log('Starting directory: ' + process.cwd()); + try { + process.chdir('/tmp'); + console.log('New directory: ' + process.cwd()); + } + catch (err) { + console.log('chdir: ' + err); + } -Example: +## process.config - /usr/local/bin/node - - -## process.execArgv - -This is the set of Node.js-specific command line options from the -executable that started the process. These options do not show up in -`process.argv`, and do not include the Node.js executable, the name of -the script, or any options following the script name. These options -are useful in order to spawn child processes with the same execution -environment as the parent. - -Example: - - $ node --harmony script.js --version - -results in process.execArgv: - - ['--harmony'] - -and process.argv: - - ['/usr/local/bin/node', 'script.js', '--version'] +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 +the "config.gypi" file that was produced when running the `./configure` script. +An example of the possible output looks like: -## process.abort() + { target_defaults: + { cflags: [], + default_configuration: 'Release', + defines: [], + include_dirs: [], + libraries: [] }, + variables: + { host_arch: 'x64', + node_install_npm: 'true', + node_prefix: '', + node_shared_cares: 'false', + node_shared_http_parser: 'false', + node_shared_libuv: 'false', + node_shared_zlib: 'false', + node_use_dtrace: 'false', + node_use_openssl: 'true', + node_shared_openssl: 'false', + strict_aliasing: 'true', + target_arch: 'x64', + v8_use_snapshot: 'true' } } -This causes Node.js to emit an abort. This will cause Node.js to exit and -generate a core file. +## process.cwd() -## process.chdir(directory) +Returns the current working directory of the process. -Changes the current working directory of the process or throws an exception if that fails. + console.log('Current directory: ' + process.cwd()); - console.log('Starting directory: ' + process.cwd()); - try { - process.chdir('/tmp'); - console.log('New directory: ' + process.cwd()); - } - catch (err) { - console.log('chdir: ' + err); - } +## process.disconnect() +Close the IPC channel to the parent process, allowing this child to exit +gracefully once there are no other connections keeping it alive. +Identical to the parent process's +[ChildProcess.disconnect()](child_process.html#child_process_child_disconnect). -## process.cwd() +If Node.js was not spawned with an IPC channel, `process.disconnect()` will be +undefined. -Returns the current working directory of the process. +### process.connected - console.log('Current directory: ' + process.cwd()); +* {Boolean} Set to false after `process.disconnect()` is called +If `process.connected` is false, it is no longer possible to send messages. ## process.env @@ -451,6 +390,34 @@ But this will: process.env.foo = 'bar'; console.log(process.env.foo); +## process.execArgv + +This is the set of Node.js-specific command line options from the +executable that started the process. These options do not show up in +`process.argv`, and do not include the Node.js executable, the name of +the script, or any options following the script name. These options +are useful in order to spawn child processes with the same execution +environment as the parent. + +Example: + + $ node --harmony script.js --version + +results in process.execArgv: + + ['--harmony'] + +and process.argv: + + ['/usr/local/bin/node', 'script.js', '--version'] + +## process.execPath + +This is the absolute pathname of the executable that started the process. + +Example: + + /usr/local/bin/node ## process.exit([code]) @@ -463,7 +430,6 @@ To exit with a 'failure' code: The shell that executed Node.js should see the exit code as 1. - ## process.exitCode A number which will be the process exit code, when the process either @@ -473,20 +439,6 @@ a code. Specifying a code to `process.exit(code)` will override any previous setting of `process.exitCode`. - -## process.getgid() - -Note: this function is only available on POSIX platforms (i.e. not Windows, -Android) - -Gets the group identity of the process. (See getgid(2).) -This is the numerical group id, not the group name. - - if (process.getgid) { - console.log('Current gid: ' + process.getgid()); - } - - ## process.getegid() Note: this function is only available on POSIX platforms (i.e. not Windows, @@ -499,62 +451,6 @@ This is the numerical group id, not the group name. console.log('Current gid: ' + process.getegid()); } - -## process.setgid(id) - -Note: this function is only available on POSIX platforms (i.e. not Windows, -Android) - -Sets the group identity of the process. (See setgid(2).) This accepts either -a numerical ID or a groupname string. If a groupname is specified, this method -blocks while resolving it to a numerical ID. - - if (process.getgid && process.setgid) { - console.log('Current gid: ' + process.getgid()); - try { - process.setgid(501); - console.log('New gid: ' + process.getgid()); - } - catch (err) { - console.log('Failed to set gid: ' + err); - } - } - - -## process.setegid(id) - -Note: this function is only available on POSIX platforms (i.e. not Windows, -Android) - -Sets the effective group identity of the process. (See setegid(2).) -This accepts either a numerical ID or a groupname string. If a groupname -is specified, this method blocks while resolving it to a numerical ID. - - if (process.getegid && process.setegid) { - console.log('Current gid: ' + process.getegid()); - try { - process.setegid(501); - console.log('New gid: ' + process.getegid()); - } - catch (err) { - console.log('Failed to set gid: ' + err); - } - } - - -## process.getuid() - -Note: this function is only available on POSIX platforms (i.e. not Windows, -Android) - -Gets the user identity of the process. (See getuid(2).) -This is the numerical userid, not the username. - - if (process.getuid) { - console.log('Current uid: ' + process.getuid()); - } - - ## process.geteuid() Note: this function is only available on POSIX platforms (i.e. not Windows, @@ -567,68 +463,58 @@ This is the numerical userid, not the username. console.log('Current uid: ' + process.geteuid()); } - -## process.setuid(id) +## process.getgid() Note: this function is only available on POSIX platforms (i.e. not Windows, Android) -Sets the user identity of the process. (See setuid(2).) This accepts either -a numerical ID or a username string. If a username is specified, this method -blocks while resolving it to a numerical ID. +Gets the group identity of the process. (See getgid(2).) +This is the numerical group id, not the group name. - if (process.getuid && process.setuid) { - console.log('Current uid: ' + process.getuid()); - try { - process.setuid(501); - console.log('New uid: ' + process.getuid()); - } - catch (err) { - console.log('Failed to set uid: ' + err); - } + if (process.getgid) { + console.log('Current gid: ' + process.getgid()); } - -## process.seteuid(id) +## process.getgroups() Note: this function is only available on POSIX platforms (i.e. not Windows, Android) -Sets the effective user identity of the process. (See seteuid(2).) -This accepts either a numerical ID or a username string. If a username -is specified, this method blocks while resolving it to a numerical ID. - - if (process.geteuid && process.seteuid) { - console.log('Current uid: ' + process.geteuid()); - try { - process.seteuid(501); - console.log('New uid: ' + process.geteuid()); - } - catch (err) { - console.log('Failed to set uid: ' + err); - } - } - +Returns an array with the supplementary group IDs. POSIX leaves it unspecified +if the effective group ID is included but Node.js ensures it always is. -## process.getgroups() +## process.getuid() Note: this function is only available on POSIX platforms (i.e. not Windows, Android) -Returns an array with the supplementary group IDs. POSIX leaves it unspecified -if the effective group ID is included but Node.js ensures it always is. +Gets the user identity of the process. (See getuid(2).) +This is the numerical userid, not the username. + if (process.getuid) { + console.log('Current uid: ' + process.getuid()); + } -## process.setgroups(groups) +## process.hrtime() -Note: this function is only available on POSIX platforms (i.e. not Windows, -Android) +Returns the current high-resolution real time in a `[seconds, nanoseconds]` +tuple Array. It is relative to an arbitrary time in the past. It is not +related to the time of day and therefore not subject to clock drift. The +primary use is for measuring performance between intervals. -Sets the supplementary group IDs. This is a privileged operation, meaning you -need to be root or have the CAP_SETGID capability. +You may pass in the result of a previous call to `process.hrtime()` to get +a diff reading, useful for benchmarks and measuring intervals: -The list can contain group IDs, group names or both. + var time = process.hrtime(); + // [ 1800216, 25 ] + + setTimeout(function() { + var diff = process.hrtime(time); + // [ 1, 552 ] + console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]); + // benchmark took 1000000527 nanoseconds + }, 1000); ## process.initgroups(user, extra_group) @@ -649,106 +535,21 @@ Some care needs to be taken when dropping privileges. Example: process.setgid(1000); // drop root gid console.log(process.getgroups()); // [ 27, 30, 46, 1000 ] +## process.kill(pid[, signal]) -## process.version +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 +'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'. +See [Signal Events](#process_signal_events) and kill(2) for more information. -A compiled-in property that exposes `NODE_VERSION`. +Will throw an error if target does not exist, and as a special case, a signal +of `0` can be used to test for the existence of a process. - console.log('Version: ' + process.version); +Note that even though the name of this function is `process.kill`, it is really +just a signal sender, like the `kill` system call. The signal sent may do +something other than kill the target process. -## process.versions - -A property exposing version strings of Node.js and its dependencies. - - console.log(process.versions); - -Will print something like: - - { http_parser: '2.3.0', - node: '1.1.1', - v8: '4.1.0.14', - uv: '1.3.0', - zlib: '1.2.8', - ares: '1.10.0-DEV', - modules: '43', - icu: '55.1', - openssl: '1.0.1k' } - -## process.config - -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 -the "config.gypi" file that was produced when running the `./configure` script. - -An example of the possible output looks like: - - { target_defaults: - { cflags: [], - default_configuration: 'Release', - defines: [], - include_dirs: [], - libraries: [] }, - variables: - { host_arch: 'x64', - node_install_npm: 'true', - node_prefix: '', - node_shared_cares: 'false', - node_shared_http_parser: 'false', - node_shared_libuv: 'false', - node_shared_zlib: 'false', - node_use_dtrace: 'false', - node_use_openssl: 'true', - node_shared_openssl: 'false', - strict_aliasing: 'true', - target_arch: 'x64', - v8_use_snapshot: 'true' } } - -## process.release - -An Object containing metadata related to the current release, including URLs -for the source tarball and headers-only tarball. - -`process.release` contains the following properties: - -* `name`: a string with a value that will always be `"node"` for Node.js. For - legacy io.js releases, this will be `"io.js"`. -* `sourceUrl`: a complete URL pointing to a _.tar.gz_ file containing the - source of the current release. -* `headersUrl`: a complete URL pointing to a _.tar.gz_ file containing only - the header files for the current release. This file is significantly smaller - than the full source file and can be used for compiling add-ons against - Node.js. -* `libUrl`: a complete URL pointing to an _node.lib_ file matching the - architecture and version of the current release. This file is used for - compiling add-ons against Node.js. _This property is only present on Windows - builds of Node.js and will be missing on all other platforms._ - -e.g. - - { name: 'node', - sourceUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0.tar.gz', - headersUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0-headers.tar.gz', - libUrl: 'https://nodejs.org/download/release/v4.0.0/win-x64/node.lib' } - -In custom builds from non-release versions of the source tree, only the -`name` property may be present. The additional properties should not be -relied upon to exist. - -## process.kill(pid[, signal]) - -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 -'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'. -See [Signal Events](#process_signal_events) and kill(2) for more information. - -Will throw an error if target does not exist, and as a special case, a signal -of `0` can be used to test for the existence of a process. - -Note that even though the name of this function is `process.kill`, it is really -just a signal sender, like the `kill` system call. The signal sent may do -something other than kill the target process. - -Example of sending a signal to yourself: +Example of sending a signal to yourself: process.on('SIGHUP', function() { console.log('Got SIGHUP signal.'); @@ -764,42 +565,16 @@ Example of sending a signal to yourself: Note: When SIGUSR1 is received by Node.js it starts the debugger, see [Signal Events](#process_signal_events). -## process.pid - -The PID of the process. - - console.log('This process is pid ' + process.pid); - - -## process.title - -Getter/setter to set what is displayed in 'ps'. - -When used as a setter, the maximum length is platform-specific and probably -short. - -On Linux and OS X, it's limited to the size of the binary name plus the -length of the command line arguments because it overwrites the argv memory. - -v0.8 allowed for longer process title strings by also overwriting the environ -memory but that was potentially insecure/confusing in some (rather obscure) -cases. - - -## process.arch - -What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`. - - console.log('This processor architecture is ' + process.arch); - - -## process.platform - -What platform you're running on: -`'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'` +## process.mainModule - console.log('This platform is ' + process.platform); +Alternate way to retrieve +[`require.main`](modules.html#modules_accessing_the_main_module). +The difference is that if the main module changes at runtime, `require.main` +might still refer to the original main module in modules that were required +before the change occurred. Generally it's safe to assume that the two refer +to the same module. +As with `require.main`, it will be `undefined` if there was no entry script. ## process.memoryUsage() @@ -818,7 +593,6 @@ This will generate: `heapTotal` and `heapUsed` refer to V8's memory usage. - ## process.nextTick(callback[, arg][, ...]) * `callback` {Function} @@ -895,45 +669,49 @@ event loop **before** additional I/O is processed. As a result, recursively setting nextTick callbacks will block any I/O from happening, just like a `while(true);` loop. -## process.umask([mask]) - -Sets or reads the process's file mode creation mask. Child processes inherit -the mask from the parent process. Returns the old mask if `mask` argument is -given, otherwise returns the current mask. - - var oldmask, newmask = 0022; +## process.pid - oldmask = process.umask(newmask); - console.log('Changed umask from: ' + oldmask.toString(8) + - ' to ' + newmask.toString(8)); +The PID of the process. + console.log('This process is pid ' + process.pid); -## process.uptime() +## process.platform -Number of seconds Node.js has been running. +What platform you're running on: +`'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'` + console.log('This platform is ' + process.platform); -## process.hrtime() +## process.release -Returns the current high-resolution real time in a `[seconds, nanoseconds]` -tuple Array. It is relative to an arbitrary time in the past. It is not -related to the time of day and therefore not subject to clock drift. The -primary use is for measuring performance between intervals. +An Object containing metadata related to the current release, including URLs +for the source tarball and headers-only tarball. -You may pass in the result of a previous call to `process.hrtime()` to get -a diff reading, useful for benchmarks and measuring intervals: +`process.release` contains the following properties: - var time = process.hrtime(); - // [ 1800216, 25 ] +* `name`: a string with a value that will always be `"node"` for Node.js. For + legacy io.js releases, this will be `"io.js"`. +* `sourceUrl`: a complete URL pointing to a _.tar.gz_ file containing the + source of the current release. +* `headersUrl`: a complete URL pointing to a _.tar.gz_ file containing only + the header files for the current release. This file is significantly smaller + than the full source file and can be used for compiling add-ons against + Node.js. +* `libUrl`: a complete URL pointing to an _node.lib_ file matching the + architecture and version of the current release. This file is used for + compiling add-ons against Node.js. _This property is only present on Windows + builds of Node.js and will be missing on all other platforms._ - setTimeout(function() { - var diff = process.hrtime(time); - // [ 1, 552 ] +e.g. - console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]); - // benchmark took 1000000527 nanoseconds - }, 1000); + { name: 'node', + sourceUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0.tar.gz', + headersUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0-headers.tar.gz', + libUrl: 'https://nodejs.org/download/release/v4.0.0/win-x64/node.lib' } +In custom builds from non-release versions of the source tree, only the +`name` property may be present. The additional properties should not be +relied upon to exist. ## process.send(message[, sendHandle][, callback]) @@ -947,36 +725,221 @@ event on the parent's `ChildProcess` object. If Node.js was not spawned with an IPC channel, `process.send()` will be undefined. +## process.setegid(id) -## process.disconnect() +Note: this function is only available on POSIX platforms (i.e. not Windows, +Android) -Close the IPC channel to the parent process, allowing this child to exit -gracefully once there are no other connections keeping it alive. +Sets the effective group identity of the process. (See setegid(2).) +This accepts either a numerical ID or a groupname string. If a groupname +is specified, this method blocks while resolving it to a numerical ID. -Identical to the parent process's -[ChildProcess.disconnect()](child_process.html#child_process_child_disconnect). + if (process.getegid && process.setegid) { + console.log('Current gid: ' + process.getegid()); + try { + process.setegid(501); + console.log('New gid: ' + process.getegid()); + } + catch (err) { + console.log('Failed to set gid: ' + err); + } + } -If Node.js was not spawned with an IPC channel, `process.disconnect()` will be -undefined. +## process.seteuid(id) +Note: this function is only available on POSIX platforms (i.e. not Windows, +Android) -### process.connected +Sets the effective user identity of the process. (See seteuid(2).) +This accepts either a numerical ID or a username string. If a username +is specified, this method blocks while resolving it to a numerical ID. -* {Boolean} Set to false after `process.disconnect()` is called + if (process.geteuid && process.seteuid) { + console.log('Current uid: ' + process.geteuid()); + try { + process.seteuid(501); + console.log('New uid: ' + process.geteuid()); + } + catch (err) { + console.log('Failed to set uid: ' + err); + } + } -If `process.connected` is false, it is no longer possible to send messages. +## process.setgid(id) +Note: this function is only available on POSIX platforms (i.e. not Windows, +Android) -## process.mainModule +Sets the group identity of the process. (See setgid(2).) This accepts either +a numerical ID or a groupname string. If a groupname is specified, this method +blocks while resolving it to a numerical ID. -Alternate way to retrieve -[`require.main`](modules.html#modules_accessing_the_main_module). -The difference is that if the main module changes at runtime, `require.main` -might still refer to the original main module in modules that were required -before the change occurred. Generally it's safe to assume that the two refer -to the same module. + if (process.getgid && process.setgid) { + console.log('Current gid: ' + process.getgid()); + try { + process.setgid(501); + console.log('New gid: ' + process.getgid()); + } + catch (err) { + console.log('Failed to set gid: ' + err); + } + } -As with `require.main`, it will be `undefined` if there was no entry script. +## process.setgroups(groups) + +Note: this function is only available on POSIX platforms (i.e. not Windows, +Android) + +Sets the supplementary group IDs. This is a privileged operation, meaning you +need to be root or have the CAP_SETGID capability. + +The list can contain group IDs, group names or both. + +## process.setuid(id) + +Note: this function is only available on POSIX platforms (i.e. not Windows, +Android) + +Sets the user identity of the process. (See setuid(2).) This accepts either +a numerical ID or a username string. If a username is specified, this method +blocks while resolving it to a numerical ID. + + if (process.getuid && process.setuid) { + console.log('Current uid: ' + process.getuid()); + try { + process.setuid(501); + console.log('New uid: ' + process.getuid()); + } + catch (err) { + console.log('Failed to set uid: ' + err); + } + } + +## process.stderr + +A writable stream to stderr (on fd `2`). + +`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` +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 +should be a very rare occurrence indeed.) + +## process.stdin + +A `Readable Stream` for stdin (on fd `0`). + +Example of opening standard input and listening for both events: + + process.stdin.setEncoding('utf8'); + + process.stdin.on('readable', function() { + var chunk = process.stdin.read(); + if (chunk !== null) { + process.stdout.write('data: ' + chunk); + } + }); + + process.stdin.on('end', function() { + process.stdout.write('end'); + }); + +As a Stream, `process.stdin` can also be used in "old" mode that is compatible +with scripts written for node.js prior to v0.10. +For more information see +[Stream compatibility](stream.html#stream_compatibility_with_older_node_js_versions). + +In "old" Streams mode the stdin stream is paused by default, so one +must call `process.stdin.resume()` to read from it. Note also that calling +`process.stdin.resume()` itself would switch stream to "old" mode. + +If you are starting a new project you should prefer a more recent "new" Streams +mode over "old" one. + +## process.stdout + +A `Writable Stream` to `stdout` (on fd `1`). + +For example, a `console.log` equivalent could look like this: + + console.log = function(msg) { + process.stdout.write(msg + '\n'); + }; + +`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` +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 +should be a very rare occurrence indeed.) + +To check if Node.js is being run in a TTY context, read the `isTTY` property +on `process.stderr`, `process.stdout`, or `process.stdin`: + + $ node -p "Boolean(process.stdin.isTTY)" + true + $ echo "foo" | node -p "Boolean(process.stdin.isTTY)" + false + + $ node -p "Boolean(process.stdout.isTTY)" + true + $ node -p "Boolean(process.stdout.isTTY)" | cat + false + +See [the tty docs](tty.html#tty_tty) for more information. + +## process.title + +Getter/setter to set what is displayed in 'ps'. + +When used as a setter, the maximum length is platform-specific and probably +short. + +On Linux and OS X, it's limited to the size of the binary name plus the +length of the command line arguments because it overwrites the argv memory. + +v0.8 allowed for longer process title strings by also overwriting the environ +memory but that was potentially insecure/confusing in some (rather obscure) +cases. + +## process.umask([mask]) + +Sets or reads the process's file mode creation mask. Child processes inherit +the mask from the parent process. Returns the old mask if `mask` argument is +given, otherwise returns the current mask. + + var oldmask, newmask = 0022; + + oldmask = process.umask(newmask); + console.log('Changed umask from: ' + oldmask.toString(8) + + ' to ' + newmask.toString(8)); + +## process.uptime() + +Number of seconds Node.js has been running. + +## process.version + +A compiled-in property that exposes `NODE_VERSION`. + + console.log('Version: ' + process.version); + +## process.versions + +A property exposing version strings of Node.js and its dependencies. + + console.log(process.versions); + +Will print something like: + + { http_parser: '2.3.0', + node: '1.1.1', + v8: '4.1.0.14', + uv: '1.3.0', + zlib: '1.2.8', + ares: '1.10.0-DEV', + modules: '43', + icu: '55.1', + openssl: '1.0.1k' } [ChildProcess.send()]: child_process.html#child_process_child_send_message_sendhandle_callback [EventEmitter]: events.html#events_class_events_eventemitter From 98113155d7458a2fd3f6d813d66b2f446c8376df Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Thu, 5 Nov 2015 14:15:39 -0500 Subject: [PATCH 30/32] doc: sort net alphabetically Reorders, with minimal contextual duplication, the net documentation alphabetically. --- doc/api/net.markdown | 713 +++++++++++++++++++++++-------------------- 1 file changed, 379 insertions(+), 334 deletions(-) diff --git a/doc/api/net.markdown b/doc/api/net.markdown index 7b328adeab1ed6..c2d8fb3e7c3669 100644 --- a/doc/api/net.markdown +++ b/doc/api/net.markdown @@ -6,176 +6,82 @@ The `net` module provides you with an asynchronous network wrapper. It contains functions for creating both servers and clients (called streams). You can include this module with `require('net');`. -## net.createServer([options][, connectionListener]) - -Creates a new server. The `connectionListener` argument is -automatically set as a listener for the ['connection'][] event. - -`options` is an object with the following defaults: - - { - allowHalfOpen: false, - pauseOnConnect: false - } +## Class: net.Server -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 -non-readable, but still writable. You should call the `end()` method explicitly. -See ['end'][] event for more information. +This class is used to create a TCP or local server. -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 -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()`. +`net.Server` is an [EventEmitter][] with the following events: -Here is an example of an echo server which listens for connections -on port 8124: +### Event: 'close' - var net = require('net'); - var server = net.createServer(function(c) { //'connection' listener - console.log('client connected'); - c.on('end', function() { - console.log('client disconnected'); - }); - c.write('hello\r\n'); - c.pipe(c); - }); - server.listen(8124, function() { //'listening' listener - console.log('server bound'); - }); +Emitted when the server closes. Note that if connections exist, this +event is not emitted until all connections are ended. -Test this by using `telnet`: +### Event: 'connection' - telnet localhost 8124 +* {Socket object} The connection object -To listen on the socket `/tmp/echo.sock` the third line from the last would -just be changed to +Emitted when a new connection is made. `socket` is an instance of +`net.Socket`. - server.listen('/tmp/echo.sock', function() { //'listening' listener +### Event: 'error' -Use `nc` to connect to a UNIX domain socket server: +* {Error Object} - nc -U /tmp/echo.sock +Emitted when an error occurs. The ['close'][] event will be called directly +following this event. See example in discussion of `server.listen`. -## net.connect(options[, connectListener]) -## net.createConnection(options[, connectListener]) +### Event: 'listening' -A factory function, which returns a new ['net.Socket'](#net_class_net_socket) -and automatically connects with the supplied `options`. +Emitted when the server has been bound after calling `server.listen`. -The options are passed to both the ['net.Socket'](#net_class_net_socket) -constructor and the ['socket.connect'](#net_socket_connect_options_connectlistener) -method. +### server.address() -The `connectListener` parameter will be added as a listener for the -['connect'][] event once. +Returns the bound address, the address family name and port of the server +as reported by the operating system. +Useful to find which port was assigned when giving getting an OS-assigned address. +Returns an object with three properties, e.g. +`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` -Here is an example of a client of the previously described echo server: +Example: - var net = require('net'); - var client = net.connect({port: 8124}, - function() { //'connect' listener - console.log('connected to server!'); - client.write('world!\r\n'); - }); - client.on('data', function(data) { - console.log(data.toString()); - client.end(); - }); - client.on('end', function() { - console.log('disconnected from server'); + var server = net.createServer(function (socket) { + socket.end("goodbye\n"); }); -To connect on the socket `/tmp/echo.sock` the second line would just be -changed to - - var client = net.connect({path: '/tmp/echo.sock'}); - -## net.connect(port[, host][, connectListener]) -## net.createConnection(port[, host][, connectListener]) - -A factory function, which returns a new -['net.Socket'](#net_class_net_socket) and automatically connects to the -supplied `port` and `host`. - -If `host` is omitted, `'localhost'` will be assumed. - -The `connectListener` parameter will be added as a listener for the -['connect'][] event once. - -## net.connect(path[, connectListener]) -## net.createConnection(path[, connectListener]) - -A factory function, which returns a new unix -['net.Socket'](#net_class_net_socket) and automatically connects to the -supplied `path`. - -The `connectListener` parameter will be added as a listener for the -['connect'][] event once. - -## Class: net.Server - -This class is used to create a TCP or local server. - -### server.listen(port[, hostname][, backlog][, callback]) - -Begin accepting connections on the specified `port` and `hostname`. If the -`hostname` is omitted, the server will accept connections on any IPv6 address -(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A -port value of zero will assign a random port. - -Backlog is the maximum length of the queue of pending connections. -The actual length will be determined by your OS through sysctl settings such as -`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this -parameter is 511 (not 512). - -This function is asynchronous. When the server has been bound, -['listening'][] event will be emitted. The last parameter `callback` -will be added as a listener for the ['listening'][] event. - -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 -would be to wait a second and then try again. This can be done with - - server.on('error', function (e) { - if (e.code == 'EADDRINUSE') { - console.log('Address in use, retrying...'); - setTimeout(function () { - server.close(); - server.listen(PORT, HOST); - }, 1000); - } + // grab a random port. + server.listen(function() { + address = server.address(); + console.log("opened server on %j", address); }); -(Note: All sockets in Node.js set `SO_REUSEADDR` already) +Don't call `server.address()` until the `'listening'` event has been emitted. +### server.close([callback]) -### server.listen(path[, callback]) +Stops the server from accepting new connections and keeps existing +connections. This function is asynchronous, the server is finally +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 +that event, it will be called with an Error as its only argument if the server +was not open when it was closed. -* `path` {String} -* `callback` {Function} +### server.connections -Start a local socket server listening for connections on the given `path`. + Stability: 0 - Deprecated: Use [server.getConnections][] instead. -This function is asynchronous. When the server has been bound, -['listening'][] event will be emitted. The last parameter `callback` -will be added as a listener for the ['listening'][] event. +The number of concurrent connections on the server. -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 -permissions checks as would be done on file creation, will be visible in the -filesystem, and will *persist until unlinked*. +This becomes `null` when sending a socket to a child with +`child_process.fork()`. To poll forks and get current number of active +connections use asynchronous `server.getConnections` instead. -On Windows, the local domain is implemented using a named pipe. The path *must* -refer to an entry in `\\?\pipe\` or `\\.\pipe\`. Any characters are permitted, -but the latter may do some processing of pipe names, such as resolving `..` -sequences. Despite appearances, the pipe name space is flat. Pipes will *not -persist*, they are removed when the last reference to them is closed. Do not -forget JavaScript string escaping requires paths to be specified with -double-backslashes, such as: +### server.getConnections(callback) - net.createServer().listen( - path.join('\\\\?\\pipe', process.cwd(), 'myctl')) +Asynchronously get the number of concurrent connections on the server. Works +when sockets were sent to forks. + +Callback should take two arguments `err` and `count`. ### server.listen(handle[, callback]) @@ -224,52 +130,64 @@ shown below. exclusive: true }); -### server.close([callback]) +### server.listen(path[, callback]) -Stops the server from accepting new connections and keeps existing -connections. This function is asynchronous, the server is finally -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 -that event, it will be called with an Error as its only argument if the server -was not open when it was closed. +* `path` {String} +* `callback` {Function} -### server.address() +Start a local socket server listening for connections on the given `path`. -Returns the bound address, the address family name and port of the server -as reported by the operating system. -Useful to find which port was assigned when giving getting an OS-assigned address. -Returns an object with three properties, e.g. -`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` +This function is asynchronous. When the server has been bound, +['listening'][] event will be emitted. The last parameter `callback` +will be added as a listener for the ['listening'][] event. -Example: +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 +permissions checks as would be done on file creation, will be visible in the +filesystem, and will *persist until unlinked*. - var server = net.createServer(function (socket) { - socket.end("goodbye\n"); - }); +On Windows, the local domain is implemented using a named pipe. The path *must* +refer to an entry in `\\?\pipe\` or `\\.\pipe\`. Any characters are permitted, +but the latter may do some processing of pipe names, such as resolving `..` +sequences. Despite appearances, the pipe name space is flat. Pipes will *not +persist*, they are removed when the last reference to them is closed. Do not +forget JavaScript string escaping requires paths to be specified with +double-backslashes, such as: - // grab a random port. - server.listen(function() { - address = server.address(); - console.log("opened server on %j", address); - }); + net.createServer().listen( + path.join('\\\\?\\pipe', process.cwd(), 'myctl')) -Don't call `server.address()` until the `'listening'` event has been emitted. +### server.listen(port[, hostname][, backlog][, callback]) -### server.unref() +Begin accepting connections on the specified `port` and `hostname`. If the +`hostname` is omitted, the server will accept connections on any IPv6 address +(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A +port value of zero will assign a random port. -Calling `unref` on a server will allow the program to exit if this is the only -active server in the event system. If the server is already `unref`d calling -`unref` again will have no effect. +Backlog is the maximum length of the queue of pending connections. +The actual length will be determined by your OS through sysctl settings such as +`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this +parameter is 511 (not 512). -Returns `server`. +This function is asynchronous. When the server has been bound, +['listening'][] event will be emitted. The last parameter `callback` +will be added as a listener for the ['listening'][] event. -### server.ref() +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 +would be to wait a second and then try again. This can be done with -Opposite of `unref`, calling `ref` on a previously `unref`d server will *not* -let the program exit if it's the only server left (the default behavior). If -the server is `ref`d calling `ref` again will have no effect. + server.on('error', function (e) { + if (e.code == 'EADDRINUSE') { + console.log('Address in use, retrying...'); + setTimeout(function () { + server.close(); + server.listen(PORT, HOST); + }, 1000); + } + }); -Returns `server`. +(Note: All sockets in Node.js set `SO_REUSEADDR` already) ### server.maxConnections @@ -279,47 +197,21 @@ high. It is not recommended to use this option once a socket has been sent to a child with `child_process.fork()`. -### server.connections - - Stability: 0 - Deprecated: Use [server.getConnections][] instead. - -The number of concurrent connections on the server. - -This becomes `null` when sending a socket to a child with -`child_process.fork()`. To poll forks and get current number of active -connections use asynchronous `server.getConnections` instead. - -### server.getConnections(callback) - -Asynchronously get the number of concurrent connections on the server. Works -when sockets were sent to forks. - -Callback should take two arguments `err` and `count`. - -`net.Server` is an [EventEmitter][] with the following events: - -### Event: 'listening' - -Emitted when the server has been bound after calling `server.listen`. - -### Event: 'connection' - -* {Socket object} The connection object - -Emitted when a new connection is made. `socket` is an instance of -`net.Socket`. +### server.ref() -### Event: 'close' +Opposite of `unref`, calling `ref` on a previously `unref`d server will *not* +let the program exit if it's the only server left (the default behavior). If +the server is `ref`d calling `ref` again will have no effect. -Emitted when the server closes. Note that if connections exist, this -event is not emitted until all connections are ended. +Returns `server`. -### Event: 'error' +### server.unref() -* {Error Object} +Calling `unref` on a server will allow the program to exit if this is the only +active server in the event system. If the server is already `unref`d calling +`unref` again will have no effect. -Emitted when an error occurs. The ['close'][] event will be called directly -following this event. See example in discussion of `server.listen`. +Returns `server`. ## Class: net.Socket @@ -345,44 +237,76 @@ Set `readable` and/or `writable` to `true` to allow reads and/or writes on this socket (NOTE: Works only when `fd` is passed). About `allowHalfOpen`, refer to `createServer()` and `'end'` event. -### socket.connect(options[, connectListener]) +`net.Socket` instances are [EventEmitter][] with the following events: -Opens the connection for a given socket. +### Event: 'close' -For TCP sockets, `options` argument should be an object which specifies: +* `had_error` {Boolean} `true` if the socket had a transmission error. - - `port`: Port the client should connect to (Required). +Emitted once the socket is fully closed. The argument `had_error` is a boolean +which says if the socket was closed due to a transmission error. - - `host`: Host the client should connect to. Defaults to `'localhost'`. +### Event: 'connect' - - `localAddress`: Local interface to bind to for network connections. +Emitted when a socket connection is successfully established. +See `connect()`. - - `localPort`: Local port to bind to for network connections. +### Event: 'data' - - `family` : Version of IP stack. Defaults to `4`. +* {Buffer object} - - `lookup` : Custom lookup function. Defaults to `dns.lookup`. +Emitted when data is received. The argument `data` will be a `Buffer` or +`String`. Encoding of data is set by `socket.setEncoding()`. +(See the [Readable Stream][] section for more information.) -For local domain sockets, `options` argument should be an object which -specifies: +Note that the __data will be lost__ if there is no listener when a `Socket` +emits a `'data'` event. - - `path`: Path the client should connect to (Required). +### Event: 'drain' -Normally this method is not needed, as `net.createConnection` opens the -socket. Use this only if you are implementing a custom Socket. +Emitted when the write buffer becomes empty. Can be used to throttle uploads. -This function is asynchronous. When the ['connect'][] event is emitted the -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. +See also: the return values of `socket.write()` -The `connectListener` parameter will be added as a listener for the -['connect'][] event. +### Event: 'end' -### socket.connect(port[, host][, connectListener]) -### socket.connect(path[, connectListener]) +Emitted when the other end of the socket sends a FIN packet. -As [socket.connect(options[, connectListener])](#net_socket_connect_options_connectlistener), -with options either as either `{port: port, host: host}` or `{path: path}`. +By default (`allowHalfOpen == false`) the socket will destroy its file +descriptor once it has written out its pending write queue. However, by +setting `allowHalfOpen == true` the socket will not automatically `end()` +its side allowing the user to write arbitrary amounts of data, with the +caveat that the user is required to `end()` their side now. + +### Event: 'error' + +* {Error object} + +Emitted when an error occurs. The `'close'` event will be called directly +following this event. + +### Event: 'lookup' + +Emitted after resolving the hostname but before connecting. +Not applicable to UNIX sockets. + +* `err` {Error | Null} The error object. See [dns.lookup()][]. +* `address` {String} The IP address. +* `family` {String | Null} The address type. See [dns.lookup()][]. + +### Event: 'timeout' + +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. + +See also: `socket.setTimeout()` + +### socket.address() + +Returns the bound address, the address family name and port of the +socket as reported by the operating system. Returns an object with +three properties, e.g. +`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` ### socket.bufferSize @@ -402,23 +326,57 @@ encoded, so the exact number of bytes is not known.) Users who experience large or growing `bufferSize` should attempt to "throttle" the data flows in their program with `pause()` and `resume()`. +### socket.bytesRead -### socket.setEncoding([encoding]) +The amount of received bytes. -Set the encoding for the socket as a Readable Stream. See -[stream.setEncoding()][] for more information. +### socket.bytesWritten -### socket.write(data[, encoding][, callback]) +The amount of bytes sent. -Sends data on the socket. The second parameter specifies the encoding in the -case of a string--it defaults to UTF8 encoding. +### socket.connect(options[, connectListener]) -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. -`'drain'` will be emitted when the buffer is again free. +Opens the connection for a given socket. -The optional `callback` parameter will be executed when the data is finally -written out - this may not be immediately. +For TCP sockets, `options` argument should be an object which specifies: + + - `port`: Port the client should connect to (Required). + + - `host`: Host the client should connect to. Defaults to `'localhost'`. + + - `localAddress`: Local interface to bind to for network connections. + + - `localPort`: Local port to bind to for network connections. + + - `family` : Version of IP stack. Defaults to `4`. + + - `lookup` : Custom lookup function. Defaults to `dns.lookup`. + +For local domain sockets, `options` argument should be an object which +specifies: + + - `path`: Path the client should connect to (Required). + +Normally this method is not needed, as `net.createConnection` opens the +socket. Use this only if you are implementing a custom Socket. + +This function is asynchronous. When the ['connect'][] event is emitted the +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. + +The `connectListener` parameter will be added as a listener for the +['connect'][] event. + +### socket.connect(path[, connectListener]) +### socket.connect(port[, host][, connectListener]) + +As [socket.connect(options[, connectListener])](#net_socket_connect_options_connectlistener), +with options either as either `{port: port, host: host}` or `{path: path}`. + +### socket.destroy() + +Ensures that no more I/O activity happens on this socket. Only necessary in +case of errors (parse error or so). ### socket.end([data][, encoding]) @@ -428,44 +386,52 @@ server will still send some data. If `data` is specified, it is equivalent to calling `socket.write(data, encoding)` followed by `socket.end()`. -### socket.destroy() +### socket.localAddress -Ensures that no more I/O activity happens on this socket. Only necessary in -case of errors (parse error or so). +The string representation of the local IP address the remote client is +connecting on. For example, if you are listening on `'0.0.0.0'` and the +client connects on `'192.168.1.1'`, the value would be `'192.168.1.1'`. + +### socket.localPort + +The numeric representation of the local port. For example, +`80` or `21`. ### socket.pause() Pauses the reading of data. That is, `'data'` events will not be emitted. Useful to throttle back an upload. -### socket.resume() +### socket.ref() -Resumes reading after a call to `pause()`. +Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not* +let the program exit if it's the only socket left (the default behavior). If +the socket is `ref`d calling `ref` again will have no effect. -### socket.setTimeout(timeout[, callback]) +Returns `socket`. -Sets the socket to timeout after `timeout` milliseconds of inactivity on -the socket. By default `net.Socket` do not have a timeout. +### socket.remoteAddress -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()` -or `destroy()` the socket. +The string representation of the remote IP address. For example, +`'74.125.127.100'` or `'2001:4860:a005::68'`. -If `timeout` is 0, then the existing idle timeout is disabled. +### socket.remoteFamily -The optional `callback` parameter will be added as a one time listener for the -`'timeout'` event. +The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. -Returns `socket`. +### socket.remotePort -### socket.setNoDelay([noDelay]) +The numeric representation of the remote port. For example, +`80` or `21`. -Disables the Nagle algorithm. By default TCP connections use the Nagle -algorithm, they buffer data before sending it off. Setting `true` for -`noDelay` will immediately fire off data each time `socket.write()` is called. -`noDelay` defaults to `true`. +### socket.resume() -Returns `socket`. +Resumes reading after a call to `pause()`. + +### socket.setEncoding([encoding]) + +Set the encoding for the socket as a Readable Stream. See +[stream.setEncoding()][] for more information. ### socket.setKeepAlive([enable][, initialDelay]) @@ -480,12 +446,30 @@ initialDelay will leave the value unchanged from the default Returns `socket`. -### socket.address() +### socket.setNoDelay([noDelay]) -Returns the bound address, the address family name and port of the -socket as reported by the operating system. Returns an object with -three properties, e.g. -`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` +Disables the Nagle algorithm. By default TCP connections use the Nagle +algorithm, they buffer data before sending it off. Setting `true` for +`noDelay` will immediately fire off data each time `socket.write()` is called. +`noDelay` defaults to `true`. + +Returns `socket`. + +### socket.setTimeout(timeout[, callback]) + +Sets the socket to timeout after `timeout` milliseconds of inactivity on +the socket. By default `net.Socket` do not have 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()` +or `destroy()` the socket. + +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 +`'timeout'` event. + +Returns `socket`. ### socket.unref() @@ -495,113 +479,174 @@ active socket in the event system. If the socket is already `unref`d calling Returns `socket`. -### socket.ref() +### socket.write(data[, encoding][, callback]) -Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not* -let the program exit if it's the only socket left (the default behavior). If -the socket is `ref`d calling `ref` again will have no effect. +Sends data on the socket. The second parameter specifies the encoding in the +case of a string--it defaults to UTF8 encoding. -Returns `socket`. +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. +`'drain'` will be emitted when the buffer is again free. -### socket.remoteAddress +The optional `callback` parameter will be executed when the data is finally +written out - this may not be immediately. -The string representation of the remote IP address. For example, -`'74.125.127.100'` or `'2001:4860:a005::68'`. +## net.connect(options[, connectListener]) -### socket.remoteFamily +A factory function, which returns a new ['net.Socket'](#net_class_net_socket) +and automatically connects with the supplied `options`. -The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. +The options are passed to both the ['net.Socket'](#net_class_net_socket) +constructor and the ['socket.connect'](#net_socket_connect_options_connectlistener) +method. -### socket.remotePort +The `connectListener` parameter will be added as a listener for the +['connect'][] event once. -The numeric representation of the remote port. For example, -`80` or `21`. +Here is an example of a client of the previously described echo server: -### socket.localAddress + var net = require('net'); + var client = net.connect({port: 8124}, + function() { //'connect' listener + console.log('connected to server!'); + client.write('world!\r\n'); + }); + client.on('data', function(data) { + console.log(data.toString()); + client.end(); + }); + client.on('end', function() { + console.log('disconnected from server'); + }); -The string representation of the local IP address the remote client is -connecting on. For example, if you are listening on `'0.0.0.0'` and the -client connects on `'192.168.1.1'`, the value would be `'192.168.1.1'`. +To connect on the socket `/tmp/echo.sock` the second line would just be +changed to -### socket.localPort + var client = net.connect({path: '/tmp/echo.sock'}); -The numeric representation of the local port. For example, -`80` or `21`. +## net.connect(path[, connectListener]) -### socket.bytesRead +A factory function, which returns a new unix +['net.Socket'](#net_class_net_socket) and automatically connects to the +supplied `path`. -The amount of received bytes. +The `connectListener` parameter will be added as a listener for the +['connect'][] event once. -### socket.bytesWritten +## net.connect(port[, host][, connectListener]) -The amount of bytes sent. +A factory function, which returns a new +['net.Socket'](#net_class_net_socket) and automatically connects to the +supplied `port` and `host`. +If `host` is omitted, `'localhost'` will be assumed. -`net.Socket` instances are [EventEmitter][] with the following events: +The `connectListener` parameter will be added as a listener for the +['connect'][] event once. -### Event: 'lookup' +## net.createConnection(options[, connectListener]) -Emitted after resolving the hostname but before connecting. -Not applicable to UNIX sockets. +A factory function, which returns a new ['net.Socket'](#net_class_net_socket) +and automatically connects with the supplied `options`. -* `err` {Error | Null} The error object. See [dns.lookup()][]. -* `address` {String} The IP address. -* `family` {String | Null} The address type. See [dns.lookup()][]. +The options are passed to both the ['net.Socket'](#net_class_net_socket) +constructor and the ['socket.connect'](#net_socket_connect_options_connectlistener) +method. -### Event: 'connect' +The `connectListener` parameter will be added as a listener for the +['connect'][] event once. -Emitted when a socket connection is successfully established. -See `connect()`. +Here is an example of a client of the previously described echo server: -### Event: 'data' + var net = require('net'); + var client = net.connect({port: 8124}, + function() { //'connect' listener + console.log('connected to server!'); + client.write('world!\r\n'); + }); + client.on('data', function(data) { + console.log(data.toString()); + client.end(); + }); + client.on('end', function() { + console.log('disconnected from server'); + }); -* {Buffer object} +To connect on the socket `/tmp/echo.sock` the second line would just be +changed to -Emitted when data is received. The argument `data` will be a `Buffer` or -`String`. Encoding of data is set by `socket.setEncoding()`. -(See the [Readable Stream][] section for more information.) + var client = net.connect({path: '/tmp/echo.sock'}); -Note that the __data will be lost__ if there is no listener when a `Socket` -emits a `'data'` event. +## net.createConnection(path[, connectListener]) -### Event: 'end' +A factory function, which returns a new unix +['net.Socket'](#net_class_net_socket) and automatically connects to the +supplied `path`. -Emitted when the other end of the socket sends a FIN packet. +The `connectListener` parameter will be added as a listener for the +['connect'][] event once. -By default (`allowHalfOpen == false`) the socket will destroy its file -descriptor once it has written out its pending write queue. However, by -setting `allowHalfOpen == true` the socket will not automatically `end()` -its side allowing the user to write arbitrary amounts of data, with the -caveat that the user is required to `end()` their side now. +## net.createConnection(port[, host][, connectListener]) +A factory function, which returns a new +['net.Socket'](#net_class_net_socket) and automatically connects to the +supplied `port` and `host`. -### Event: 'timeout' +If `host` is omitted, `'localhost'` will be assumed. -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 `connectListener` parameter will be added as a listener for the +['connect'][] event once. -See also: `socket.setTimeout()` +## net.createServer([options][, connectionListener]) +Creates a new server. The `connectionListener` argument is +automatically set as a listener for the ['connection'][] event. -### Event: 'drain' +`options` is an object with the following defaults: -Emitted when the write buffer becomes empty. Can be used to throttle uploads. + { + allowHalfOpen: false, + pauseOnConnect: false + } -See also: the return values of `socket.write()` +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 +non-readable, but still writable. You should call the `end()` method explicitly. +See ['end'][] event for more information. -### Event: 'error' +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 +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()`. -* {Error object} +Here is an example of an echo server which listens for connections +on port 8124: -Emitted when an error occurs. The `'close'` event will be called directly -following this event. + var net = require('net'); + var server = net.createServer(function(c) { //'connection' listener + console.log('client connected'); + c.on('end', function() { + console.log('client disconnected'); + }); + c.write('hello\r\n'); + c.pipe(c); + }); + server.listen(8124, function() { //'listening' listener + console.log('server bound'); + }); -### Event: 'close' +Test this by using `telnet`: -* `had_error` {Boolean} `true` if the socket had a transmission error. + telnet localhost 8124 -Emitted once the socket is fully closed. The argument `had_error` is a boolean -which says if the socket was closed due to a transmission error. +To listen on the socket `/tmp/echo.sock` the third line from the last would +just be changed to + + server.listen('/tmp/echo.sock', function() { //'listening' listener + +Use `nc` to connect to a UNIX domain socket server: + + nc -U /tmp/echo.sock ## net.isIP(input) From e8c1e068164cbcfe8f9a898df52a254dcbaee92d Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Thu, 5 Nov 2015 14:54:10 -0500 Subject: [PATCH 31/32] doc: sort stream alphabetically Reorders, with no contextual changes, the stream documentation alphabetically. --- doc/api/stream.markdown | 1110 +++++++++++++++++++-------------------- 1 file changed, 551 insertions(+), 559 deletions(-) diff --git a/doc/api/stream.markdown b/doc/api/stream.markdown index 4dfc36e09e6648..c4d3f79ce1d88d 100644 --- a/doc/api/stream.markdown +++ b/doc/api/stream.markdown @@ -93,6 +93,17 @@ server.listen(1337); // error: Unexpected token o ``` +### Class: stream.Duplex + +Duplex streams are streams that implement both the [Readable][] and +[Writable][] interfaces. See above for usage. + +Examples of Duplex streams include: + +* [tcp sockets][] +* [zlib streams][] +* [crypto streams][] + ### Class: stream.Readable @@ -145,52 +156,13 @@ Examples of readable streams include: * [child process stdout and stderr][] * [process.stdin][] -#### Event: 'readable' - -When a chunk of data can be read from the stream, it will emit a -`'readable'` event. - -In some cases, listening for a `'readable'` event will cause some data -to be read into the internal buffer from the underlying system, if it -hadn't already. - -```javascript -var readable = getReadableStreamSomehow(); -readable.on('readable', function() { - // there is some data to read now -}); -``` - -Once the internal buffer is drained, a `readable` event will fire -again when more data is available. - -The `readable` event is not emitted in the "flowing" mode with the -sole exception of the last one, on end-of-stream. - -The 'readable' event indicates that the stream has new information: -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, -`.read()` will return null. For instance, in the following example, `foo.txt` -is an empty file: - -```javascript -var fs = require('fs'); -var rr = fs.createReadStream('foo.txt'); -rr.on('readable', function() { - console.log('readable:', rr.read()); -}); -rr.on('end', function() { - console.log('end'); -}); -``` +#### Event: 'close' -The output of running this script is: +Emitted when the stream and any of its underlying resources (a file +descriptor, for example) have been closed. The event indicates that +no more events will be emitted, and no further computation will occur. -``` -bash-3.2$ node test.js -readable: null -end -``` +Not all streams will emit the 'close' event. #### Event: 'data' @@ -228,101 +200,75 @@ readable.on('end', function() { }); ``` -#### Event: 'close' - -Emitted when the stream and any of its underlying resources (a file -descriptor, for example) have been closed. The event indicates that -no more events will be emitted, and no further computation will occur. - -Not all streams will emit the 'close' event. - #### Event: 'error' * {Error Object} Emitted if there was an error receiving data. -#### readable.read([size]) - -* `size` {Number} Optional argument to specify how much data to read. -* Return {String | Buffer | null} - -The `read()` method pulls some data out of the internal buffer and -returns it. If there is no data available, then it will return -`null`. - -If you pass in a `size` argument, then it will return that many -bytes. If `size` bytes are not available, then it will return `null`, -unless we've ended, in which case it will return the data remaining -in the buffer. +#### Event: 'readable' -If you do not specify a `size` argument, then it will return all the -data in the internal buffer. +When a chunk of data can be read from the stream, it will emit a +`'readable'` event. -This method should only be called in paused mode. In flowing mode, -this method is called automatically until the internal buffer is -drained. +In some cases, listening for a `'readable'` event will cause some data +to be read into the internal buffer from the underlying system, if it +hadn't already. ```javascript var readable = getReadableStreamSomehow(); readable.on('readable', function() { - var chunk; - while (null !== (chunk = readable.read())) { - console.log('got %d bytes of data', chunk.length); - } + // there is some data to read now }); ``` -If this method returns a data chunk, then it will also trigger the -emission of a [`'data'` event][]. - -Note that calling `readable.read([size])` after the `end` event has been -triggered will return `null`. No runtime error will be raised. - -#### readable.setEncoding(encoding) - -* `encoding` {String} The encoding to use. -* Return: `this` +Once the internal buffer is drained, a `readable` event will fire +again when more data is available. -Call this function to cause the stream to return strings of the -specified encoding instead of Buffer objects. For example, if you do -`readable.setEncoding('utf8')`, then the output data will be -interpreted as UTF-8 data, and returned as strings. If you do -`readable.setEncoding('hex')`, then the data will be encoded in -hexadecimal string format. +The `readable` event is not emitted in the "flowing" mode with the +sole exception of the last one, on end-of-stream. -This properly handles multi-byte characters that would otherwise be -potentially mangled if you simply pulled the Buffers directly and -called `buf.toString(encoding)` on them. If you want to read the data -as strings, always use this method. +The 'readable' event indicates that the stream has new information: +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, +`.read()` will return null. For instance, in the following example, `foo.txt` +is an empty file: ```javascript -var readable = getReadableStreamSomehow(); -readable.setEncoding('utf8'); -readable.on('data', function(chunk) { - assert.equal(typeof chunk, 'string'); - console.log('got %d characters of string data', chunk.length); +var fs = require('fs'); +var rr = fs.createReadStream('foo.txt'); +rr.on('readable', function() { + console.log('readable:', rr.read()); +}); +rr.on('end', function() { + console.log('end'); }); ``` -#### readable.resume() +The output of running this script is: -* Return: `this` +``` +bash-3.2$ node test.js +readable: null +end +``` -This method will cause the readable stream to resume emitting `data` -events. +#### readable.isPaused() -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 -its `end` event, you can call [`readable.resume()`][] to open the flow of -data. +* Return: `Boolean` + +This method returns whether or not the `readable` has been **explicitly** +paused by client code (using `readable.pause()` without a corresponding +`readable.resume()`). ```javascript -var readable = getReadableStreamSomehow(); -readable.resume(); -readable.on('end', function() { - console.log('got to the end, but did not read anything'); -}); +var readable = new stream.Readable + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false ``` #### readable.pause() @@ -346,24 +292,6 @@ readable.on('data', function(chunk) { }); ``` -#### readable.isPaused() - -* Return: `Boolean` - -This method returns whether or not the `readable` has been **explicitly** -paused by client code (using `readable.pause()` without a corresponding -`readable.resume()`). - -```javascript -var readable = new stream.Readable - -readable.isPaused() // === false -readable.pause() -readable.isPaused() // === true -readable.resume() -readable.isPaused() // === false -``` - #### readable.pipe(destination[, options]) * `destination` {[Writable][] Stream} The destination for writing data @@ -416,54 +344,137 @@ reader.on('end', function() { Note that `process.stderr` and `process.stdout` are never closed until the process exits, regardless of the specified options. -#### readable.unpipe([destination]) +#### readable.read([size]) -* `destination` {[Writable][] Stream} Optional specific stream to unpipe +* `size` {Number} Optional argument to specify how much data to read. +* Return {String | Buffer | null} -This method will remove the hooks set up for a previous `pipe()` call. +The `read()` method pulls some data out of the internal buffer and +returns it. If there is no data available, then it will return +`null`. -If the destination is not specified, then all pipes are removed. +If you pass in a `size` argument, then it will return that many +bytes. If `size` bytes are not available, then it will return `null`, +unless we've ended, in which case it will return the data remaining +in the buffer. -If the destination is specified, but no pipe is set up for it, then -this is a no-op. +If you do not specify a `size` argument, then it will return all the +data in the internal buffer. + +This method should only be called in paused mode. In flowing mode, +this method is called automatically until the internal buffer is +drained. ```javascript var readable = getReadableStreamSomehow(); -var writable = fs.createWriteStream('file.txt'); -// All the data from readable goes into 'file.txt', -// but only for the first second -readable.pipe(writable); -setTimeout(function() { - console.log('stop writing to file.txt'); - readable.unpipe(writable); - console.log('manually close the file stream'); - writable.end(); -}, 1000); +readable.on('readable', function() { + var chunk; + while (null !== (chunk = readable.read())) { + console.log('got %d bytes of data', chunk.length); + } +}); ``` -#### readable.unshift(chunk) +If this method returns a data chunk, then it will also trigger the +emission of a [`'data'` event][]. -* `chunk` {Buffer | String} Chunk of data to unshift onto the read queue +Note that calling `readable.read([size])` after the `end` event has been +triggered will return `null`. No runtime error will be raised. -This is useful in certain cases where a stream is being consumed by a -parser, which needs to "un-consume" some data that it has -optimistically pulled out of the source, so that the stream can be -passed on to some other party. +#### readable.resume() -Note that `stream.unshift(chunk)` cannot be called after the `end` event -has been triggered; a runtime error will be raised. +* Return: `this` -If you find that you must often call `stream.unshift(chunk)` in your -programs, consider implementing a [Transform][] stream instead. (See API -for Stream Implementors, below.) +This method will cause the readable stream to resume emitting `data` +events. + +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 +its `end` event, you can call [`readable.resume()`][] to open the flow of +data. ```javascript -// Pull off a header delimited by \n\n -// use unshift() if we get too much -// Call the callback with (error, header, stream) -var StringDecoder = require('string_decoder').StringDecoder; -function parseHeader(stream, callback) { - stream.on('error', callback); +var readable = getReadableStreamSomehow(); +readable.resume(); +readable.on('end', function() { + console.log('got to the end, but did not read anything'); +}); +``` + +#### readable.setEncoding(encoding) + +* `encoding` {String} The encoding to use. +* Return: `this` + +Call this function to cause the stream to return strings of the +specified encoding instead of Buffer objects. For example, if you do +`readable.setEncoding('utf8')`, then the output data will be +interpreted as UTF-8 data, and returned as strings. If you do +`readable.setEncoding('hex')`, then the data will be encoded in +hexadecimal string format. + +This properly handles multi-byte characters that would otherwise be +potentially mangled if you simply pulled the Buffers directly and +called `buf.toString(encoding)` on them. If you want to read the data +as strings, always use this method. + +```javascript +var readable = getReadableStreamSomehow(); +readable.setEncoding('utf8'); +readable.on('data', function(chunk) { + assert.equal(typeof chunk, 'string'); + console.log('got %d characters of string data', chunk.length); +}); +``` + +#### readable.unpipe([destination]) + +* `destination` {[Writable][] Stream} Optional specific stream to unpipe + +This method will remove the hooks set up for a previous `pipe()` call. + +If the destination is not specified, then all pipes are removed. + +If the destination is specified, but no pipe is set up for it, then +this is a no-op. + +```javascript +var readable = getReadableStreamSomehow(); +var writable = fs.createWriteStream('file.txt'); +// All the data from readable goes into 'file.txt', +// but only for the first second +readable.pipe(writable); +setTimeout(function() { + console.log('stop writing to file.txt'); + readable.unpipe(writable); + console.log('manually close the file stream'); + writable.end(); +}, 1000); +``` + +#### readable.unshift(chunk) + +* `chunk` {Buffer | String} Chunk of data to unshift onto the read queue + +This is useful in certain cases where a stream is being consumed by a +parser, which needs to "un-consume" some data that it has +optimistically pulled out of the source, so that the stream can be +passed on to some other party. + +Note that `stream.unshift(chunk)` cannot be called after the `end` event +has been triggered; a runtime error will be raised. + +If you find that you must often call `stream.unshift(chunk)` in your +programs, consider implementing a [Transform][] stream instead. (See API +for Stream Implementors, below.) + +```javascript +// Pull off a header delimited by \n\n +// use unshift() if we get too much +// Call the callback with (error, header, stream) +var StringDecoder = require('string_decoder').StringDecoder; +function parseHeader(stream, callback) { + stream.on('error', callback); stream.on('readable', onReadable); var decoder = new StringDecoder('utf8'); var header = ''; @@ -528,6 +539,16 @@ myReader.on('readable', function() { }); ``` +### Class: stream.Transform + +Transform streams are [Duplex][] streams where the output is in some way +computed from the input. They implement both the [Readable][] and +[Writable][] interfaces. See above for usage. + +Examples of Transform streams include: + +* [zlib streams][] +* [crypto streams][] ### Class: stream.Writable @@ -547,25 +568,6 @@ Examples of writable streams include: * [child process stdin](child_process.html#child_process_child_stdin) * [process.stdout][], [process.stderr][] -#### writable.write(chunk[, encoding][, callback]) - -* `chunk` {String | Buffer} The data to write -* `encoding` {String} The encoding, if `chunk` is a String -* `callback` {Function} Callback for when this chunk of data is flushed -* Returns: {Boolean} True if the data was handled completely. - -This method writes some data to the underlying system, and calls the -supplied callback once the data has been fully handled. - -The return value indicates if you should continue writing right now. -If the data had to be buffered internally, then it will return -`false`. Otherwise, it will return `true`. - -This return value is strictly advisory. You MAY continue to write, -even if it returns `false`. However, writes will be buffered in -memory, so it is best not to do this excessively. Instead, wait for -the `drain` event before writing more data. - #### Event: 'drain' If a [`writable.write(chunk)`][] call returns false, then the `drain` @@ -600,40 +602,11 @@ function writeOneMillionTimes(writer, data, encoding, callback) { } ``` -#### writable.cork() - -Forces buffering of all writes. - -Buffered data will be flushed either at `.uncork()` or at `.end()` call. - -#### writable.uncork() - -Flush all data, buffered since `.cork()` call. - -#### writable.setDefaultEncoding(encoding) - -* `encoding` {String} The new default encoding - -Sets the default encoding for a writable stream. - -#### writable.end([chunk][, encoding][, callback]) - -* `chunk` {String | Buffer} Optional data to write -* `encoding` {String} The encoding, if `chunk` is a String -* `callback` {Function} Optional callback for when the stream is finished - -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. +#### Event: 'error' -Calling [`write()`][] after calling [`end()`][] will raise an error. +* {Error object} -```javascript -// write 'hello, ' and then end with 'world!' -var file = fs.createWriteStream('example.txt'); -file.write('hello, '); -file.end('world!'); -// writing more now is not allowed! -``` +Emitted if there was an error when writing or piping data. #### Event: 'finish' @@ -686,34 +659,59 @@ reader.pipe(writer); reader.unpipe(writer); ``` -#### Event: 'error' +#### writable.cork() -* {Error object} +Forces buffering of all writes. -Emitted if there was an error when writing or piping data. +Buffered data will be flushed either at `.uncork()` or at `.end()` call. -### Class: stream.Duplex +#### writable.end([chunk][, encoding][, callback]) -Duplex streams are streams that implement both the [Readable][] and -[Writable][] interfaces. See above for usage. +* `chunk` {String | Buffer} Optional data to write +* `encoding` {String} The encoding, if `chunk` is a String +* `callback` {Function} Optional callback for when the stream is finished -Examples of Duplex streams include: +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. -* [tcp sockets][] -* [zlib streams][] -* [crypto streams][] +Calling [`write()`][] after calling [`end()`][] will raise an error. +```javascript +// write 'hello, ' and then end with 'world!' +var file = fs.createWriteStream('example.txt'); +file.write('hello, '); +file.end('world!'); +// writing more now is not allowed! +``` -### Class: stream.Transform +#### writable.setDefaultEncoding(encoding) -Transform streams are [Duplex][] streams where the output is in some way -computed from the input. They implement both the [Readable][] and -[Writable][] interfaces. See above for usage. +* `encoding` {String} The new default encoding -Examples of Transform streams include: +Sets the default encoding for a writable stream. -* [zlib streams][] -* [crypto streams][] +#### writable.uncork() + +Flush all data, buffered since `.cork()` call. + +#### writable.write(chunk[, encoding][, callback]) + +* `chunk` {String | Buffer} The data to write +* `encoding` {String} The encoding, if `chunk` is a String +* `callback` {Function} Callback for when this chunk of data is flushed +* Returns: {Boolean} True if the data was handled completely. + +This method writes some data to the underlying system, and calls the +supplied callback once the data has been fully handled. + +The return value indicates if you should continue writing right now. +If the data had to be buffered internally, then it will return +`false`. Otherwise, it will return `true`. + +This return value is strictly advisory. You MAY continue to write, +even if it returns `false`. However, writes will be buffered in +memory, so it is best not to do this excessively. Instead, wait for +the `drain` event before writing more data. ## API for Stream Implementors @@ -796,6 +794,49 @@ methods described in [API for Stream Consumers][] above. Otherwise, you can potentially cause adverse side effects in programs that consume your streaming interfaces. +### Class: stream.Duplex + + + +A "duplex" stream is one that is both Readable and Writable, such as a +TCP socket connection. + +Note that `stream.Duplex` is an abstract class designed to be extended +with an underlying implementation of the `_read(size)` and +[`_write(chunk, encoding, callback)`][] methods as you would with a +Readable or Writable stream class. + +Since JavaScript doesn't have multiple prototypal inheritance, this +class prototypally inherits from Readable, and then parasitically from +Writable. It is thus up to the user to implement both the lowlevel +`_read(n)` method as well as the lowlevel +[`_write(chunk, encoding, callback)`][] method on extension duplex classes. + +#### new stream.Duplex(options) + +* `options` {Object} Passed to both Writable and Readable + constructors. Also has the following fields: + * `allowHalfOpen` {Boolean} Default=true. If set to `false`, then + the stream will automatically end the readable side when the + writable side ends and vice versa. + * `readableObjectMode` {Boolean} Default=false. Sets `objectMode` + for readable side of the stream. Has no effect if `objectMode` + is `true`. + * `writableObjectMode` {Boolean} Default=false. Sets `objectMode` + for writable side of the stream. Has no effect if `objectMode` + is `true`. + +In classes that extend the Duplex class, make sure to call the +constructor so that the buffering settings can be properly +initialized. + +### Class: stream.PassThrough + +This is a trivial implementation of a [Transform][] stream that simply +passes the input bytes across to the output. Its purpose is mainly +for examples and testing, but there are occasionally use cases where +it can come in handy as a building block for novel sorts of streams. + ### Class: stream.Readable @@ -807,15 +848,115 @@ Please see above under [API for Stream Consumers][] for how to consume streams in your programs. What follows is an explanation of how to implement Readable streams in your programs. -#### Example: A Counting Stream - - - -This is a basic example of a Readable stream. It emits the numerals -from 1 to 1,000,000 in ascending order, and then ends. +#### new stream.Readable([options]) -```javascript -var Readable = require('stream').Readable; +* `options` {Object} + * `highWaterMark` {Number} The maximum number of bytes to store in + the internal buffer before ceasing to read from the underlying + resource. Default=16kb, or 16 for `objectMode` streams + * `encoding` {String} If specified, then buffers will be decoded to + strings using the specified encoding. Default=null + * `objectMode` {Boolean} Whether this stream should behave + as a stream of objects. Meaning that stream.read(n) returns + a single value instead of a Buffer of size n. Default=false + +In classes that extend the Readable class, make sure to call the +Readable constructor so that the buffering settings can be properly +initialized. + +#### readable.\_read(size) + +* `size` {Number} Number of bytes to read asynchronously + +Note: **Implement this method, but do NOT call it directly.** + +This method is prefixed with an underscore because it is internal to the +class that defines it and should only be called by the internal Readable +class methods. All Readable stream implementations must provide a _read +method to fetch data from the underlying resource. + +When _read is called, if data is available from the resource, `_read` should +start pushing that data into the read queue by calling `this.push(dataChunk)`. +`_read` should continue reading from the resource and pushing data until push +returns false, at which point it should stop reading from the resource. Only +when _read is called again after it has stopped should it start reading +more data from the resource and pushing that data onto the queue. + +Note: once the `_read()` method is called, it will not be called again until +the `push` method is called. + +The `size` argument is advisory. Implementations where a "read" is a +single call that returns data can use this to know how much data to +fetch. Implementations where that is not relevant, such as TCP or +TLS, may ignore this argument, and simply provide data whenever it +becomes available. There is no need, for example to "wait" until +`size` bytes are available before calling [`stream.push(chunk)`][]. + +#### readable.push(chunk[, encoding]) + +* `chunk` {Buffer | null | String} Chunk of data to push into the read queue +* `encoding` {String} Encoding of String chunks. Must be a valid + Buffer encoding, such as `'utf8'` or `'ascii'` +* return {Boolean} Whether or not more pushes should be performed + +Note: **This method should be called by Readable implementors, NOT +by consumers of Readable streams.** + +If a value other than null is passed, The `push()` method adds a chunk of data +into the queue for subsequent stream processors to consume. If `null` is +passed, it signals the end of the stream (EOF), after which no more data +can be written. + +The data added with `push` can be pulled out by calling the `read()` method +when the `'readable'`event fires. + +This API is designed to be as flexible as possible. For example, +you may be wrapping a lower-level source which has some sort of +pause/resume mechanism, and a data callback. In those cases, you +could wrap the low-level source object by doing something like this: + +```javascript +// source is an object with readStop() and readStart() methods, +// and an `ondata` member that gets called when it has data, and +// an `onend` member that gets called when the data is over. + +util.inherits(SourceWrapper, Readable); + +function SourceWrapper(options) { + Readable.call(this, options); + + this._source = getLowlevelSourceObject(); + var self = this; + + // Every time there's data, we push it into the internal buffer. + this._source.ondata = function(chunk) { + // if push() returns false, then we need to stop reading from source + if (!self.push(chunk)) + self._source.readStop(); + }; + + // When the source ends, we push the EOF-signaling `null` chunk + this._source.onend = function() { + self.push(null); + }; +} + +// _read will be called when the stream wants to pull more data in +// the advisory size argument is ignored in this case. +SourceWrapper.prototype._read = function(size) { + this._source.readStart(); +}; +``` + +#### Example: A Counting Stream + + + +This is a basic example of a Readable stream. It emits the numerals +from 1 to 1,000,000 in ascending order, and then ends. + +```javascript +var Readable = require('stream').Readable; var util = require('util'); util.inherits(Counter, Readable); @@ -951,220 +1092,6 @@ SimpleProtocol.prototype._read = function(n) { // with the parsed header data. ``` - -#### new stream.Readable([options]) - -* `options` {Object} - * `highWaterMark` {Number} The maximum number of bytes to store in - the internal buffer before ceasing to read from the underlying - resource. Default=16kb, or 16 for `objectMode` streams - * `encoding` {String} If specified, then buffers will be decoded to - strings using the specified encoding. Default=null - * `objectMode` {Boolean} Whether this stream should behave - as a stream of objects. Meaning that stream.read(n) returns - a single value instead of a Buffer of size n. Default=false - -In classes that extend the Readable class, make sure to call the -Readable constructor so that the buffering settings can be properly -initialized. - -#### readable.\_read(size) - -* `size` {Number} Number of bytes to read asynchronously - -Note: **Implement this method, but do NOT call it directly.** - -This method is prefixed with an underscore because it is internal to the -class that defines it and should only be called by the internal Readable -class methods. All Readable stream implementations must provide a _read -method to fetch data from the underlying resource. - -When _read is called, if data is available from the resource, `_read` should -start pushing that data into the read queue by calling `this.push(dataChunk)`. -`_read` should continue reading from the resource and pushing data until push -returns false, at which point it should stop reading from the resource. Only -when _read is called again after it has stopped should it start reading -more data from the resource and pushing that data onto the queue. - -Note: once the `_read()` method is called, it will not be called again until -the `push` method is called. - -The `size` argument is advisory. Implementations where a "read" is a -single call that returns data can use this to know how much data to -fetch. Implementations where that is not relevant, such as TCP or -TLS, may ignore this argument, and simply provide data whenever it -becomes available. There is no need, for example to "wait" until -`size` bytes are available before calling [`stream.push(chunk)`][]. - -#### readable.push(chunk[, encoding]) - -* `chunk` {Buffer | null | String} Chunk of data to push into the read queue -* `encoding` {String} Encoding of String chunks. Must be a valid - Buffer encoding, such as `'utf8'` or `'ascii'` -* return {Boolean} Whether or not more pushes should be performed - -Note: **This method should be called by Readable implementors, NOT -by consumers of Readable streams.** - -If a value other than null is passed, The `push()` method adds a chunk of data -into the queue for subsequent stream processors to consume. If `null` is -passed, it signals the end of the stream (EOF), after which no more data -can be written. - -The data added with `push` can be pulled out by calling the `read()` method -when the `'readable'`event fires. - -This API is designed to be as flexible as possible. For example, -you may be wrapping a lower-level source which has some sort of -pause/resume mechanism, and a data callback. In those cases, you -could wrap the low-level source object by doing something like this: - -```javascript -// source is an object with readStop() and readStart() methods, -// and an `ondata` member that gets called when it has data, and -// an `onend` member that gets called when the data is over. - -util.inherits(SourceWrapper, Readable); - -function SourceWrapper(options) { - Readable.call(this, options); - - this._source = getLowlevelSourceObject(); - var self = this; - - // Every time there's data, we push it into the internal buffer. - this._source.ondata = function(chunk) { - // if push() returns false, then we need to stop reading from source - if (!self.push(chunk)) - self._source.readStop(); - }; - - // When the source ends, we push the EOF-signaling `null` chunk - this._source.onend = function() { - self.push(null); - }; -} - -// _read will be called when the stream wants to pull more data in -// the advisory size argument is ignored in this case. -SourceWrapper.prototype._read = function(size) { - this._source.readStart(); -}; -``` - - -### Class: stream.Writable - - - -`stream.Writable` is an abstract class designed to be extended with an -underlying implementation of the [`_write(chunk, encoding, callback)`][] method. - -Please see above under [API for Stream Consumers][] for how to consume -writable streams in your programs. What follows is an explanation of -how to implement Writable streams in your programs. - -#### new stream.Writable([options]) - -* `options` {Object} - * `highWaterMark` {Number} Buffer level when [`write()`][] starts - returning false. Default=16kb, or 16 for `objectMode` streams - * `decodeStrings` {Boolean} Whether or not to decode strings into - Buffers before passing them to [`_write()`][]. Default=true - * `objectMode` {Boolean} Whether or not the `write(anyObj)` is - a valid operation. If set you can write arbitrary data instead - of only `Buffer` / `String` data. Default=false - -In classes that extend the Writable class, make sure to call the -constructor so that the buffering settings can be properly -initialized. - -#### writable.\_write(chunk, encoding, callback) - -* `chunk` {Buffer | String} The chunk to be written. Will **always** - be a buffer unless the `decodeStrings` option was set to `false`. -* `encoding` {String} If the chunk is a string, then this is the - encoding type. If chunk is a buffer, then this is the special - value - 'buffer', ignore it in this case. -* `callback` {Function} Call this function (optionally with an error - argument) when you are done processing the supplied chunk. - -All Writable stream implementations must provide a [`_write()`][] -method to send data to the underlying resource. - -Note: **This function MUST NOT be called directly.** It should be -implemented by child classes, and called by the internal Writable -class methods only. - -Call the callback using the standard `callback(error)` pattern to -signal that the write completed successfully or with an error. - -If the `decodeStrings` flag is set in the constructor options, then -`chunk` may be a string rather than a Buffer, and `encoding` will -indicate the sort of string that it is. This is to support -implementations that have an optimized handling for certain string -data encodings. If you do not explicitly set the `decodeStrings` -option to `false`, then you can safely ignore the `encoding` argument, -and assume that `chunk` will always be a Buffer. - -This method is prefixed with an underscore because it is internal to -the class that defines it, and should not be called directly by user -programs. However, you **are** expected to override this method in -your own extension classes. - -#### writable.\_writev(chunks, callback) - -* `chunks` {Array} The chunks to be written. Each chunk has following - format: `{ chunk: ..., encoding: ... }`. -* `callback` {Function} Call this function (optionally with an error - argument) when you are done processing the supplied chunks. - -Note: **This function MUST NOT be called directly.** It may be -implemented by child classes, and called by the internal Writable -class methods only. - -This function is completely optional to implement. In most cases it is -unnecessary. If implemented, it will be called with all the chunks -that are buffered in the write queue. - - -### Class: stream.Duplex - - - -A "duplex" stream is one that is both Readable and Writable, such as a -TCP socket connection. - -Note that `stream.Duplex` is an abstract class designed to be extended -with an underlying implementation of the `_read(size)` and -[`_write(chunk, encoding, callback)`][] methods as you would with a -Readable or Writable stream class. - -Since JavaScript doesn't have multiple prototypal inheritance, this -class prototypally inherits from Readable, and then parasitically from -Writable. It is thus up to the user to implement both the lowlevel -`_read(n)` method as well as the lowlevel -[`_write(chunk, encoding, callback)`][] method on extension duplex classes. - -#### new stream.Duplex(options) - -* `options` {Object} Passed to both Writable and Readable - constructors. Also has the following fields: - * `allowHalfOpen` {Boolean} Default=true. If set to `false`, then - the stream will automatically end the readable side when the - writable side ends and vice versa. - * `readableObjectMode` {Boolean} Default=false. Sets `objectMode` - for readable side of the stream. Has no effect if `objectMode` - is `true`. - * `writableObjectMode` {Boolean} Default=false. Sets `objectMode` - for writable side of the stream. Has no effect if `objectMode` - is `true`. - -In classes that extend the Duplex class, make sure to call the -constructor so that the buffering settings can be properly -initialized. - - ### Class: stream.Transform A "transform" stream is a duplex stream where the output is causally @@ -1181,14 +1108,49 @@ Rather than implement the [`_read()`][] and [`_write()`][] methods, Transform classes must implement the `_transform()` method, and may optionally also implement the `_flush()` method. (See below.) -#### new stream.Transform([options]) +#### new stream.Transform([options]) + +* `options` {Object} Passed to both Writable and Readable + constructors. + +In classes that extend the Transform class, make sure to call the +constructor so that the buffering settings can be properly +initialized. + +#### Events: 'finish' and 'end' + +The [`finish`][] and [`end`][] events are from the parent Writable +and Readable classes respectively. The `finish` event is fired after +`.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 +in `_flush` has been called. + +#### transform.\_flush(callback) + +* `callback` {Function} Call this function (optionally with an error + argument) when you are done flushing any remaining data. + +Note: **This function MUST NOT be called directly.** It MAY be implemented +by child classes, and if so, will be called by the internal Transform +class methods only. -* `options` {Object} Passed to both Writable and Readable - constructors. +In some cases, your transform operation may need to emit a bit more +data at the end of the stream. For example, a `Zlib` compression +stream will store up some internal state so that it can optimally +compress the output. At the end, however, it needs to do the best it +can with what is left, so that the data will be complete. -In classes that extend the Transform class, make sure to call the -constructor so that the buffering settings can be properly -initialized. +In those cases, you can implement a `_flush` method, which will be +called at the very end, after all the written data is consumed, but +before emitting `end` to signal the end of the readable side. Just +like with `_transform`, call `transform.push(chunk)` zero or more +times, as appropriate, and call `callback` when the flush operation is +complete. + +This method is prefixed with an underscore because it is internal to +the class that defines it, and should not be called directly by user +programs. However, you **are** expected to override this method in +your own extension classes. #### transform.\_transform(chunk, encoding, callback) @@ -1238,41 +1200,6 @@ the class that defines it, and should not be called directly by user programs. However, you **are** expected to override this method in your own extension classes. -#### transform.\_flush(callback) - -* `callback` {Function} Call this function (optionally with an error - argument) when you are done flushing any remaining data. - -Note: **This function MUST NOT be called directly.** It MAY be implemented -by child classes, and if so, will be called by the internal Transform -class methods only. - -In some cases, your transform operation may need to emit a bit more -data at the end of the stream. For example, a `Zlib` compression -stream will store up some internal state so that it can optimally -compress the output. At the end, however, it needs to do the best it -can with what is left, so that the data will be complete. - -In those cases, you can implement a `_flush` method, which will be -called at the very end, after all the written data is consumed, but -before emitting `end` to signal the end of the readable side. Just -like with `_transform`, call `transform.push(chunk)` zero or more -times, as appropriate, and call `callback` when the flush operation is -complete. - -This method is prefixed with an underscore because it is internal to -the class that defines it, and should not be called directly by user -programs. However, you **are** expected to override this method in -your own extension classes. - -#### Events: 'finish' and 'end' - -The [`finish`][] and [`end`][] events are from the parent Writable -and Readable classes respectively. The `finish` event is fired after -`.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 -in `_flush` has been called. - #### Example: `SimpleProtocol` parser v2 The example above of a simple protocol parser can be implemented @@ -1351,13 +1278,79 @@ SimpleProtocol.prototype._transform = function(chunk, encoding, done) { // with the parsed header data. ``` +### Class: stream.Writable -### Class: stream.PassThrough + -This is a trivial implementation of a [Transform][] stream that simply -passes the input bytes across to the output. Its purpose is mainly -for examples and testing, but there are occasionally use cases where -it can come in handy as a building block for novel sorts of streams. +`stream.Writable` is an abstract class designed to be extended with an +underlying implementation of the [`_write(chunk, encoding, callback)`][] method. + +Please see above under [API for Stream Consumers][] for how to consume +writable streams in your programs. What follows is an explanation of +how to implement Writable streams in your programs. + +#### new stream.Writable([options]) + +* `options` {Object} + * `highWaterMark` {Number} Buffer level when [`write()`][] starts + returning false. Default=16kb, or 16 for `objectMode` streams + * `decodeStrings` {Boolean} Whether or not to decode strings into + Buffers before passing them to [`_write()`][]. Default=true + * `objectMode` {Boolean} Whether or not the `write(anyObj)` is + a valid operation. If set you can write arbitrary data instead + of only `Buffer` / `String` data. Default=false + +In classes that extend the Writable class, make sure to call the +constructor so that the buffering settings can be properly +initialized. + +#### writable.\_write(chunk, encoding, callback) + +* `chunk` {Buffer | String} The chunk to be written. Will **always** + be a buffer unless the `decodeStrings` option was set to `false`. +* `encoding` {String} If the chunk is a string, then this is the + encoding type. If chunk is a buffer, then this is the special + value - 'buffer', ignore it in this case. +* `callback` {Function} Call this function (optionally with an error + argument) when you are done processing the supplied chunk. + +All Writable stream implementations must provide a [`_write()`][] +method to send data to the underlying resource. + +Note: **This function MUST NOT be called directly.** It should be +implemented by child classes, and called by the internal Writable +class methods only. + +Call the callback using the standard `callback(error)` pattern to +signal that the write completed successfully or with an error. + +If the `decodeStrings` flag is set in the constructor options, then +`chunk` may be a string rather than a Buffer, and `encoding` will +indicate the sort of string that it is. This is to support +implementations that have an optimized handling for certain string +data encodings. If you do not explicitly set the `decodeStrings` +option to `false`, then you can safely ignore the `encoding` argument, +and assume that `chunk` will always be a Buffer. + +This method is prefixed with an underscore because it is internal to +the class that defines it, and should not be called directly by user +programs. However, you **are** expected to override this method in +your own extension classes. + +#### writable.\_writev(chunks, callback) + +* `chunks` {Array} The chunks to be written. Each chunk has following + format: `{ chunk: ..., encoding: ... }`. +* `callback` {Function} Call this function (optionally with an error + argument) when you are done processing the supplied chunks. + +Note: **This function MUST NOT be called directly.** It may be +implemented by child classes, and called by the internal Writable +class methods only. + +This function is completely optional to implement. In most cases it is +unnecessary. If implemented, it will be called with all the chunks +that are buffered in the write queue. ## Simplified Constructor API @@ -1370,32 +1363,6 @@ This can be done by passing the appropriate methods as constructor options: Examples: -### Readable -```javascript -var readable = new stream.Readable({ - read: function(n) { - // sets this._read under the hood - } -}); -``` - -### Writable -```javascript -var writable = new stream.Writable({ - write: function(chunk, encoding, next) { - // sets this._write under the hood - } -}); - -// or - -var writable = new stream.Writable({ - writev: function(chunks, next) { - // sets this._writev under the hood - } -}); -``` - ### Duplex ```javascript var duplex = new stream.Duplex({ @@ -1419,6 +1386,15 @@ var duplex = new stream.Duplex({ }); ``` +### Readable +```javascript +var readable = new stream.Readable({ + read: function(n) { + // sets this._read under the hood + } +}); +``` + ### Transform ```javascript var transform = new stream.Transform({ @@ -1431,6 +1407,23 @@ var transform = new stream.Transform({ }); ``` +### Writable +```javascript +var writable = new stream.Writable({ + write: function(chunk, encoding, next) { + // sets this._write under the hood + } +}); + +// or + +var writable = new stream.Writable({ + writev: function(chunks, next) { + // sets this._writev under the hood + } +}); +``` + ## Streams: Under the Hood @@ -1458,40 +1451,6 @@ The purpose of streams, especially with the `pipe()` method, is to limit the buffering of data to acceptable levels, so that sources and destinations of varying speed will not overwhelm the available memory. -### `stream.read(0)` - -There are some cases where you want to trigger a refresh of the -underlying readable stream mechanisms, without actually consuming any -data. In that case, you can call `stream.read(0)`, which will always -return null. - -If the internal read buffer is below the `highWaterMark`, and the -stream is not currently reading, then calling `read(0)` will trigger -a low-level `_read` call. - -There is almost never a need to do this. However, you will see some -cases in Node.js's internals where this is done, particularly in the -Readable stream class internals. - -### `stream.push('')` - -Pushing a zero-byte string or Buffer (when not in [Object mode][]) has an -interesting side effect. Because it *is* a call to -[`stream.push()`][], it will end the `reading` process. However, it -does *not* add any data to the readable buffer, so there's nothing for -a user to consume. - -Very rarely, there are cases where you have no data to provide now, -but the consumer of your stream (or, perhaps, another bit of your own -code) will know when to check again, by calling `stream.read(0)`. In -those cases, you *may* call `stream.push('')`. - -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 -find that you have to use `stream.push('')`, please consider another -approach, because it almost certainly indicates that something is -horribly wrong. - ### Compatibility with Older Node.js Versions @@ -1649,6 +1608,39 @@ JSONParseStream.prototype._flush = function(cb) { }; ``` +### `stream.read(0)` + +There are some cases where you want to trigger a refresh of the +underlying readable stream mechanisms, without actually consuming any +data. In that case, you can call `stream.read(0)`, which will always +return null. + +If the internal read buffer is below the `highWaterMark`, and the +stream is not currently reading, then calling `read(0)` will trigger +a low-level `_read` call. + +There is almost never a need to do this. However, you will see some +cases in Node.js's internals where this is done, particularly in the +Readable stream class internals. + +### `stream.push('')` + +Pushing a zero-byte string or Buffer (when not in [Object mode][]) has an +interesting side effect. Because it *is* a call to +[`stream.push()`][], it will end the `reading` process. However, it +does *not* add any data to the readable buffer, so there's nothing for +a user to consume. + +Very rarely, there are cases where you have no data to provide now, +but the consumer of your stream (or, perhaps, another bit of your own +code) will know when to check again, by calling `stream.read(0)`. In +those cases, you *may* call `stream.push('')`. + +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 +find that you have to use `stream.push('')`, please consider another +approach, because it almost certainly indicates that something is +horribly wrong. [EventEmitter]: events.html#events_class_events_eventemitter [Object mode]: #stream_object_mode From 1b86f37de5d76024452851afa32185542fe8473f Mon Sep 17 00:00:00 2001 From: Tristian Flanagan Date: Thu, 5 Nov 2015 15:04:26 -0500 Subject: [PATCH 32/32] doc: sort tls alphabetically Reorders, with no contextual changes, the tls documentation alphabetically. --- doc/api/tls.markdown | 1133 +++++++++++++++++++++--------------------- 1 file changed, 560 insertions(+), 573 deletions(-) diff --git a/doc/api/tls.markdown b/doc/api/tls.markdown index 8e64bc98a098a2..48dbd1e63bc40d 100644 --- a/doc/api/tls.markdown +++ b/doc/api/tls.markdown @@ -40,6 +40,17 @@ To create .pfx or .p12, do this: - `certfile`: all CA certs concatenated in one file like `cat ca1-cert.pem ca2-cert.pem > ca-cert.pem` +## ALPN, NPN and SNI + + + +ALPN (Application-Layer Protocol Negotiation Extension), NPN (Next +Protocol Negotiation) and SNI (Server Name Indication) are TLS +handshake extensions allowing you: + + * ALPN/NPN - to use one TLS server for multiple protocols (HTTP, SPDY, HTTP/2) + * SNI - to use one TLS server for multiple hostnames with different SSL + certificates. ## Client-initiated renegotiation attack mitigation @@ -65,19 +76,6 @@ To test your server, connect to it with `openssl s_client -connect address:port` and tap `R` (that's the letter `R` followed by a carriage return) a few times. - -## ALPN, NPN and SNI - - - -ALPN (Application-Layer Protocol Negotiation Extension), NPN (Next -Protocol Negotiation) and SNI (Server Name Indication) are TLS -handshake extensions allowing you: - - * ALPN/NPN - to use one TLS server for multiple protocols (HTTP, SPDY, HTTP/2) - * SNI - to use one TLS server for multiple hostnames with different SSL - certificates. - ## Modifying the Default TLS Cipher suite Node.js is built with a default suite of enabled and disabled TLS ciphers. @@ -139,789 +137,778 @@ the character "E" appended to the traditional abbreviations): key-agreement protocol. Ephemeral methods may have some performance drawbacks, because key generation -is expensive. +is expensive.## Class: tls.TLSSocket +Wrapper for instance of [net.Socket][], replaces internal socket read/write +routines to perform transparent encryption/decryption of incoming/outgoing data. -## tls.getCiphers() - -Returns an array with the names of the supported SSL ciphers. - -Example: - - var ciphers = tls.getCiphers(); - console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...] - +## Class: CryptoStream -## tls.createServer(options[, secureConnectionListener]) + Stability: 0 - Deprecated: Use [tls.TLSSocket][] instead. -Creates a new [tls.Server][]. The `connectionListener` argument is -automatically set as a listener for the [secureConnection][] event. The -`options` object has these possibilities: +This is an encrypted stream. - - `pfx`: A string or `Buffer` containing the private key, certificate and - CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with - the `key`, `cert` and `ca` options.) +### cryptoStream.bytesWritten - - `key`: A string or `Buffer` containing the private key of the server in - PEM format. To support multiple keys using different algorithms, an array - can be provided. It can either be a plain array of keys, or an array of - objects in the format `{pem: key, passphrase: passphrase}`. (Required) +A proxy to the underlying socket's bytesWritten accessor, this will return +the total bytes written to the socket, *including the TLS overhead*. - - `passphrase`: A string of passphrase for the private key or pfx. +## Class: SecurePair - - `cert`: A string or `Buffer` containing the certificate key of the server in - PEM format. (Could be an array of certs). (Required) +Returned by tls.createSecurePair. - - `ca`: An array of strings or `Buffer`s of trusted certificates in PEM - format. If this is omitted several well known "root" CAs will be used, - like VeriSign. These are used to authorize connections. +### Event: 'secure' - - `crl` : Either a string or list of strings of PEM encoded CRLs (Certificate - Revocation List) +The event is emitted from the SecurePair once the pair has successfully +established a secure connection. - - `ciphers`: A string describing the ciphers to use or exclude, separated by - `:`. The default cipher suite is: +Similarly to the checking for the server 'secureConnection' event, +pair.cleartext.authorized should be checked to confirm whether the certificate +used properly authorized. - ECDHE-RSA-AES128-GCM-SHA256: - ECDHE-ECDSA-AES128-GCM-SHA256: - ECDHE-RSA-AES256-GCM-SHA384: - ECDHE-ECDSA-AES256-GCM-SHA384: - DHE-RSA-AES128-GCM-SHA256: - ECDHE-RSA-AES128-SHA256: - DHE-RSA-AES128-SHA256: - ECDHE-RSA-AES256-SHA384: - DHE-RSA-AES256-SHA384: - ECDHE-RSA-AES256-SHA256: - DHE-RSA-AES256-SHA256: - HIGH: - !aNULL: - !eNULL: - !EXPORT: - !DES: - !RC4: - !MD5: - !PSK: - !SRP: - !CAMELLIA +## Class: tls.Server - The default cipher suite prefers GCM ciphers for [Chrome's 'modern - cryptography' setting] and also prefers ECDHE and DHE ciphers for Perfect - Forward secrecy, while offering *some* backward compatibiltity. +This class is a subclass of `net.Server` and has the same methods on it. +Instead of accepting just raw TCP connections, this accepts encrypted +connections using TLS or SSL. - 128 bit AES is preferred over 192 and 256 bit AES in light of [specific - attacks affecting larger AES key sizes]. +### Event: 'clientError' - Old clients that rely on insecure and deprecated RC4 or DES-based ciphers - (like Internet Explorer 6) aren't able to complete the handshake with the default - configuration. If you absolutely must support these clients, the - [TLS recommendations] may offer a compatible cipher suite. For more details - on the format, see the [OpenSSL cipher list format documentation]. +`function (exception, tlsSocket) { }` - - `ecdhCurve`: A string describing a named curve to use for ECDH key agreement - or false to disable ECDH. +When a client connection emits an 'error' event before secure connection is +established - it will be forwarded here. - Defaults to `prime256v1` (NIST P-256). Use [crypto.getCurves()][] to obtain - a list of available curve names. On recent releases, - `openssl ecparam -list_curves` will also display the name and description of - each available elliptic curve. +`tlsSocket` is the [tls.TLSSocket][] that the error originated from. - - `dhparam`: A string or `Buffer` containing Diffie Hellman parameters, - required for Perfect Forward Secrecy. Use `openssl dhparam` to create it. - Its key length should be greater than or equal to 1024 bits, otherwise - it throws an error. It is strongly recommended to use 2048 bits or - more for stronger security. If omitted or invalid, it is silently - discarded and DHE ciphers won't be available. +### Event: 'newSession' - - `handshakeTimeout`: Abort the connection if the SSL/TLS handshake does not - finish in this many milliseconds. The default is 120 seconds. +`function (sessionId, sessionData, callback) { }` - A `'clientError'` is emitted on the `tls.Server` object whenever a handshake - times out. +Emitted on creation of TLS session. May be used to store sessions in external +storage. `callback` must be invoked eventually, otherwise no data will be +sent or received from secure connection. - - `honorCipherOrder` : When choosing a cipher, use the server's preferences - instead of the client preferences. Default: `true`. +NOTE: adding this event listener will have an effect only on connections +established after addition of event listener. - - `requestCert`: If `true` the server will request a certificate from - clients that connect and attempt to verify that certificate. Default: - `false`. +### Event: 'OCSPRequest' - - `rejectUnauthorized`: If `true` the server will reject any connection - which is not authorized with the list of supplied CAs. This option only - has an effect if `requestCert` is `true`. Default: `false`. +`function (certificate, issuer, callback) { }` - - `NPNProtocols`: An array or `Buffer` of possible NPN protocols. (Protocols - should be ordered by their priority). +Emitted when the client sends a certificate status request. You could parse +server's current certificate to obtain OCSP url and certificate id, and after +obtaining OCSP response invoke `callback(null, resp)`, where `resp` is a +`Buffer` instance. Both `certificate` and `issuer` are a `Buffer` +DER-representations of the primary and issuer's certificates. They could be used +to obtain OCSP certificate id and OCSP endpoint url. - - `ALPNProtocols`: An array or `Buffer` of possible ALPN - protocols. (Protocols should be ordered by their priority). When - the server receives both NPN and ALPN extensions from the client, - ALPN takes precedence over NPN and the server does not send an NPN - extension to the client. +Alternatively, `callback(null, null)` could be called, meaning that there is no +OCSP response. - - `SNICallback(servername, cb)`: A function that will be called if client - supports SNI TLS extension. Two argument will be passed to it: `servername`, - and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a - SecureContext instance. - (You can use `tls.createSecureContext(...)` to get proper - SecureContext). If `SNICallback` wasn't provided - default callback with - high-level API will be used (see below). +Calling `callback(err)` will result in a `socket.destroy(err)` call. - - `sessionTimeout`: An integer specifying the seconds after which TLS - session identifiers and TLS session tickets created by the server are - timed out. See [SSL_CTX_set_timeout] for more details. +Typical flow: - - `ticketKeys`: A 48-byte `Buffer` instance consisting of 16-byte prefix, - 16-byte hmac key, 16-byte AES key. You could use it to accept tls session - tickets on multiple instances of tls server. +1. Client connects to server and sends `OCSPRequest` to it (via status info + extension in ClientHello.) +2. Server receives request and invokes `OCSPRequest` event listener if present +3. Server grabs OCSP url from either `certificate` or `issuer` and performs an + [OCSP request] to the CA +4. Server receives `OCSPResponse` from CA and sends it back to client via + `callback` argument +5. Client validates the response and either destroys socket or performs a + handshake. - NOTE: Automatically shared between `cluster` module workers. +NOTE: `issuer` could be null, if the certificate is self-signed or if the issuer +is not in the root certificates list. (You could provide an issuer via `ca` +option.) - - `sessionIdContext`: A string containing an opaque identifier for session - resumption. If `requestCert` is `true`, the default is MD5 hash value - generated from command-line. Otherwise, the default is not provided. +NOTE: adding this event listener will have an effect only on connections +established after addition of event listener. - - `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force - SSL version 3. The possible values depend on your installation of - OpenSSL and are defined in the constant [SSL_METHODS][]. +NOTE: you may want to use some npm module like [asn1.js] to parse the +certificates. -Here is a simple example echo server: +### Event: 'resumeSession' - var tls = require('tls'); - var fs = require('fs'); +`function (sessionId, callback) { }` - var options = { - key: fs.readFileSync('server-key.pem'), - cert: fs.readFileSync('server-cert.pem'), +Emitted when client wants to resume previous TLS session. Event listener may +perform lookup in external storage using given `sessionId`, and invoke +`callback(null, sessionData)` once finished. If session can't be resumed +(i.e. doesn't exist in storage) one may call `callback(null, null)`. Calling +`callback(err)` will terminate incoming connection and destroy socket. - // This is necessary only if using the client certificate authentication. - requestCert: true, +NOTE: adding this event listener will have an effect only on connections +established after addition of event listener. - // This is necessary only if the client uses the self-signed certificate. - ca: [ fs.readFileSync('client-cert.pem') ] - }; +Here's an example for using TLS session resumption: - var server = tls.createServer(options, function(socket) { - console.log('server connected', - socket.authorized ? 'authorized' : 'unauthorized'); - socket.write("welcome!\n"); - socket.setEncoding('utf8'); - socket.pipe(socket); + var tlsSessionStore = {}; + server.on('newSession', function(id, data, cb) { + tlsSessionStore[id.toString('hex')] = data; + cb(); }); - server.listen(8000, function() { - console.log('server bound'); + server.on('resumeSession', function(id, cb) { + cb(null, tlsSessionStore[id.toString('hex')] || null); }); -Or +### Event: 'secureConnection' - var tls = require('tls'); - var fs = require('fs'); +`function (tlsSocket) {}` - var options = { - pfx: fs.readFileSync('server.pfx'), +This event is emitted after a new connection has been successfully +handshaked. The argument is an instance of [tls.TLSSocket][]. It has all the +common stream methods and events. - // This is necessary only if using the client certificate authentication. - requestCert: true, +`socket.authorized` is a boolean value which indicates if the +client has verified by one of the supplied certificate authorities for the +server. If `socket.authorized` is false, then +`socket.authorizationError` is set to describe how authorization +failed. Implied but worth mentioning: depending on the settings of the TLS +server, you unauthorized connections may be accepted. - }; +`socket.npnProtocol` is a string containing the selected NPN protocol +and `socket.alpnProtocol` is a string containing the selected ALPN +protocol, When both NPN and ALPN extensions are received, ALPN takes +precedence over NPN and the next protocol is selected by ALPN. When +ALPN has no selected protocol, this returns false. - var server = tls.createServer(options, function(socket) { - console.log('server connected', - socket.authorized ? 'authorized' : 'unauthorized'); - socket.write("welcome!\n"); - socket.setEncoding('utf8'); - socket.pipe(socket); - }); - server.listen(8000, function() { - console.log('server bound'); - }); -You can test this server by connecting to it with `openssl s_client`: +`socket.servername` is a string containing servername requested with +SNI. +### server.addContext(hostname, context) - openssl s_client -connect 127.0.0.1:8000 +Add secure context that will be used if client request's SNI hostname is +matching passed `hostname` (wildcards can be used). `context` can contain +`key`, `cert`, `ca` and/or any other properties from `tls.createSecureContext` +`options` argument. +### server.address() -## tls.connect(options[, callback]) -## tls.connect(port[, host][, options][, callback]) +Returns the bound address, the address family name and port of the +server as reported by the operating system. See [net.Server.address()][] for +more information. -Creates a new client connection to the given `port` and `host` (old API) or -`options.port` and `options.host`. (If `host` is omitted, it defaults to -`localhost`.) `options` should be an object which specifies: +### server.close([callback]) - - `host`: Host the client should connect to +Stops the server from accepting new connections. This function is +asynchronous, the server is finally closed when the server emits a `'close'` +event. Optionally, you can pass a callback to listen for the `'close'` event. - - `port`: Port the client should connect to +### server.connections - - `socket`: Establish secure connection on a given socket rather than - creating a new socket. If this option is specified, `host` and `port` - are ignored. +The number of concurrent connections on the server. - - `path`: Creates unix socket connection to path. If this option is - specified, `host` and `port` are ignored. +### server.getTicketKeys() - - `pfx`: A string or `Buffer` containing the private key, certificate and - CA certs of the client in PFX or PKCS12 format. +Returns `Buffer` instance holding the keys currently used for +encryption/decryption of the [TLS Session Tickets][] - - `key`: A string or `Buffer` containing the private key of the client in - PEM format. (Could be an array of keys). +### server.listen(port[, hostname][, callback]) - - `passphrase`: A string of passphrase for the private key or pfx. +Begin accepting connections on the specified `port` and `hostname`. If the +`hostname` is omitted, the server will accept connections on any IPv6 address +(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A +port value of zero will assign a random port. - - `cert`: A string or `Buffer` containing the certificate key of the client in - PEM format. (Could be an array of certs). +This function is asynchronous. The last parameter `callback` will be called +when the server has been bound. - - `ca`: An array of strings or `Buffer`s of trusted certificates in PEM - format. If this is omitted several well known "root" CAs will be used, - like VeriSign. These are used to authorize connections. +See `net.Server` for more information. - - `ciphers`: A string describing the ciphers to use or exclude, separated by - `:`. Uses the same default cipher suite as `tls.createServer`. +### server.maxConnections - - `rejectUnauthorized`: If `true`, the server certificate is verified against - the list of supplied CAs. An `'error'` event is emitted if verification - fails; `err.code` contains the OpenSSL error code. Default: `true`. +Set this property to reject connections when the server's connection count +gets high. - - `NPNProtocols`: An array of strings or `Buffer`s containing supported NPN - protocols. `Buffer`s should have the following format: - `0x05hello0x05world`, where first byte is next protocol name's - length. (Passing array should usually be much simpler: - `['hello', 'world']`.) +### server.setTicketKeys(keys) - - `ALPNProtocols`: An array of strings or `Buffer`s containing - supported ALPN protocols. `Buffer`s should have following format: - `0x05hello0x05world`, where the first byte is the next protocol - name's length. (Passing array should usually be much simpler: - `['hello', 'world']`.) +Updates the keys for encryption/decryption of the [TLS Session Tickets][]. - - `servername`: Servername for SNI (Server Name Indication) TLS extension. +NOTE: the buffer should be 48 bytes long. See server `ticketKeys` option for +more information oh how it is going to be used. - - `checkServerIdentity(servername, cert)`: Provide an override for checking - server's hostname against the certificate. Should return an error if verification - fails. Return `undefined` if passing. +NOTE: the change is effective only for the future server connections. Existing +or currently pending server connections will use previous keys. - - `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force - SSL version 3. The possible values depend on your installation of - OpenSSL and are defined in the constant [SSL_METHODS][]. +## Class: tls.TLSSocket - - `session`: A `Buffer` instance, containing TLS session. +This is a wrapped version of [net.Socket][] that does transparent encryption +of written data and all required TLS negotiation. - - `minDHSize`: Minimum size of DH parameter in bits to accept a TLS - connection. When a server offers DH parameter with a size less - than this, the TLS connection is destroyed and throws an - error. Default: 1024. +This instance implements a duplex [Stream][] interfaces. It has all the +common stream methods and events. -The `callback` parameter will be added as a listener for the -['secureConnect'][] event. +### Event: 'OCSPResponse' -`tls.connect()` returns a [tls.TLSSocket][] object. +`function (response) { }` -Here is an example of a client of echo server as described previously: +This event will be emitted if `requestOCSP` option was set. `response` is a +buffer object, containing server's OCSP response. - var tls = require('tls'); - var fs = require('fs'); +Traditionally, the `response` is a signed object from the server's CA that +contains information about server's certificate revocation status. - var options = { - // These are necessary only if using the client certificate authentication - key: fs.readFileSync('client-key.pem'), - cert: fs.readFileSync('client-cert.pem'), +### Event: 'secureConnect' - // This is necessary only if the server uses the self-signed certificate - ca: [ fs.readFileSync('server-cert.pem') ] - }; +This event is emitted after a new connection has been successfully handshaked. +The listener will be called no matter if the server's certificate was +authorized or not. It is up to the user to test `tlsSocket.authorized` +to see if the server certificate was signed by one of the specified CAs. +If `tlsSocket.authorized === false` then the error can be found in +`tlsSocket.authorizationError`. Also if ALPN or NPN was used - you can +check `tlsSocket.alpnProtocol` or `tlsSocket.npnProtocol` for the +negotiated protocol. - var socket = tls.connect(8000, options, function() { - console.log('client connected', - socket.authorized ? 'authorized' : 'unauthorized'); - process.stdin.pipe(socket); - process.stdin.resume(); - }); - socket.setEncoding('utf8'); - socket.on('data', function(data) { - console.log(data); - }); - socket.on('end', function() { - server.close(); - }); +### tlsSocket.address() -Or +Returns the bound address, the address family name and port of the +underlying socket as reported by the operating system. Returns an +object with three properties, e.g. +`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` - var tls = require('tls'); - var fs = require('fs'); +### tlsSocket.authorized - var options = { - pfx: fs.readFileSync('client.pfx') - }; +A boolean that is `true` if the peer certificate was signed by one of the +specified CAs, otherwise `false` - var socket = tls.connect(8000, options, function() { - console.log('client connected', - socket.authorized ? 'authorized' : 'unauthorized'); - process.stdin.pipe(socket); - process.stdin.resume(); - }); - socket.setEncoding('utf8'); - socket.on('data', function(data) { - console.log(data); - }); - socket.on('end', function() { - server.close(); - }); +### tlsSocket.authorizationError -## Class: tls.TLSSocket +The reason why the peer's certificate has not been verified. This property +becomes available only when `tlsSocket.authorized === false`. -Wrapper for instance of [net.Socket][], replaces internal socket read/write -routines to perform transparent encryption/decryption of incoming/outgoing data. +### tlsSocket.encrypted -## new tls.TLSSocket(socket[, options]) +Static boolean value, always `true`. May be used to distinguish TLS sockets +from regular ones. -Construct a new TLSSocket object from existing TCP socket. +### tlsSocket.getCipher() +Returns an object representing the cipher name and the SSL/TLS +protocol version of the current connection. -`socket` is an instance of [net.Socket][] +Example: +{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' } -`options` is an optional object that might contain following properties: +See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in +http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more +information. - - `secureContext`: An optional TLS context object from - `tls.createSecureContext( ... )` +### tlsSocket.getEphemeralKeyInfo() - - `isServer`: If `true` - TLS socket will be instantiated in server-mode. - Default: `false` +Returns an object representing a type, name and size of parameter of +an ephemeral key exchange in [Perfect forward Secrecy][] on a client +connection. It returns an empty object when the key exchange is not +ephemeral. As it is only supported on a client socket, it returns null +if this is called on a server socket. The supported types are 'DH' and +'ECDH'. The `name` property is only available in 'ECDH'. - - `server`: An optional [net.Server][] instance +Example: - - `requestCert`: Optional, see [tls.createSecurePair][] + { type: 'ECDH', name: 'prime256v1', size: 256 } - - `rejectUnauthorized`: Optional, see [tls.createSecurePair][] +### tlsSocket.getPeerCertificate([ detailed ]) - - `NPNProtocols`: Optional, see [tls.createServer][] +Returns an object representing the peer's certificate. The returned object has +some properties corresponding to the field of the certificate. If `detailed` +argument is `true` - the full chain with `issuer` property will be returned, +if `false` - only the top certificate without `issuer` property. - - `ALPNProtocols`: Optional, see [tls.createServer][] +Example: - - `SNICallback`: Optional, see [tls.createServer][] + { subject: + { C: 'UK', + ST: 'Acknack Ltd', + L: 'Rhys Jones', + O: 'node.js', + OU: 'Test TLS Certificate', + CN: 'localhost' }, + issuerInfo: + { C: 'UK', + ST: 'Acknack Ltd', + L: 'Rhys Jones', + O: 'node.js', + OU: 'Test TLS Certificate', + CN: 'localhost' }, + issuer: + { ... another certificate ... }, + raw: < RAW DER buffer >, + valid_from: 'Nov 11 09:52:22 2009 GMT', + valid_to: 'Nov 6 09:52:22 2029 GMT', + fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF', + serialNumber: 'B9B0D332A1AA5635' } - - `session`: Optional, a `Buffer` instance, containing TLS session +If the peer does not provide a certificate, it returns `null` or an empty +object. - - `requestOCSP`: Optional, if `true` - OCSP status request extension would - be added to client hello, and `OCSPResponse` event will be emitted on socket - before establishing secure communication +### tlsSocket.getSession() +Return ASN.1 encoded TLS session or `undefined` if none was negotiated. Could +be used to speed up handshake establishment when reconnecting to the server. -## tls.createSecureContext(details) +### tlsSocket.getTLSTicket() -Creates a credentials object, with the optional details being a -dictionary with keys: +NOTE: Works only with client TLS sockets. Useful only for debugging, for +session reuse provide `session` option to `tls.connect`. -* `pfx` : A string or buffer holding the PFX or PKCS12 encoded private - key, certificate and CA certificates -* `key`: A string or `Buffer` containing the private key of the server in - PEM format. To support multiple keys using different algorithms, an array - can be provided. It can either be a plain array of keys, or an array of - objects in the format `{pem: key, passphrase: passphrase}`. (Required) -* `passphrase` : A string of passphrase for the private key or pfx -* `cert` : A string holding the PEM encoded certificate -* `ca` : Either a string or list of strings of PEM encoded CA - certificates to trust. -* `crl` : Either a string or list of strings of PEM encoded CRLs - (Certificate Revocation List) -* `ciphers`: A string describing the ciphers to use or exclude. - Consult - - for details on the format. -* `honorCipherOrder` : When choosing a cipher, use the server's preferences - instead of the client preferences. For further details see `tls` module - documentation. +Return TLS session ticket or `undefined` if none was negotiated. -If no 'ca' details are given, then Node.js will use the default -publicly trusted list of CAs as given in -. +### tlsSocket.localAddress +The string representation of the local IP address. -## tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options]) +### tlsSocket.localPort -Creates a new secure pair object with two streams, one of which reads/writes -encrypted data, and one reads/writes cleartext data. -Generally the encrypted one is piped to/from an incoming encrypted data stream, -and the cleartext one is used as a replacement for the initial encrypted stream. +The numeric representation of the local port. - - `credentials`: A secure context object from tls.createSecureContext( ... ) +### tlsSocket.remoteAddress - - `isServer`: A boolean indicating whether this tls connection should be - opened as a server or a client. +The string representation of the remote IP address. For example, +`'74.125.127.100'` or `'2001:4860:a005::68'`. - - `requestCert`: A boolean indicating whether a server should request a - certificate from a connecting client. Only applies to server connections. +### tlsSocket.remoteFamily - - `rejectUnauthorized`: A boolean indicating whether a server should - automatically reject clients with invalid certificates. Only applies to - servers with `requestCert` enabled. +The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. - - `options`: An object with common SSL options. See [tls.TLSSocket][]. +### tlsSocket.remotePort -`tls.createSecurePair()` returns a SecurePair object with `cleartext` and -`encrypted` stream properties. +The numeric representation of the remote port. For example, `443`. -NOTE: `cleartext` has the same APIs as [tls.TLSSocket][] +### tlsSocket.renegotiate(options, callback) -## Class: SecurePair +Initiate TLS renegotiation process. The `options` may contain the following +fields: `rejectUnauthorized`, `requestCert` (See [tls.createServer][] +for details). `callback(err)` will be executed with `null` as `err`, +once the renegotiation is successfully completed. -Returned by tls.createSecurePair. +NOTE: Can be used to request peer's certificate after the secure connection +has been established. -### Event: 'secure' +ANOTHER NOTE: When running as the server, socket will be destroyed +with an error after `handshakeTimeout` timeout. -The event is emitted from the SecurePair once the pair has successfully -established a secure connection. +### tlsSocket.setMaxSendFragment(size) -Similarly to the checking for the server 'secureConnection' event, -pair.cleartext.authorized should be checked to confirm whether the certificate -used properly authorized. +Set maximum TLS fragment size (default and maximum value is: `16384`, minimum +is: `512`). Returns `true` on success, `false` otherwise. -## Class: tls.Server +Smaller fragment size decreases buffering latency on the client: large +fragments are buffered by the TLS layer until the entire fragment is received +and its integrity is verified; large fragments can span multiple roundtrips, +and their processing can be delayed due to packet loss or reordering. However, +smaller fragments add extra TLS framing bytes and CPU overhead, which may +decrease overall server throughput. -This class is a subclass of `net.Server` and has the same methods on it. -Instead of accepting just raw TCP connections, this accepts encrypted -connections using TLS or SSL. +## new tls.TLSSocket(socket[, options]) -### Event: 'secureConnection' +Construct a new TLSSocket object from existing TCP socket. -`function (tlsSocket) {}` +`socket` is an instance of [net.Socket][] -This event is emitted after a new connection has been successfully -handshaked. The argument is an instance of [tls.TLSSocket][]. It has all the -common stream methods and events. +`options` is an optional object that might contain following properties: -`socket.authorized` is a boolean value which indicates if the -client has verified by one of the supplied certificate authorities for the -server. If `socket.authorized` is false, then -`socket.authorizationError` is set to describe how authorization -failed. Implied but worth mentioning: depending on the settings of the TLS -server, you unauthorized connections may be accepted. + - `secureContext`: An optional TLS context object from + `tls.createSecureContext( ... )` -`socket.npnProtocol` is a string containing the selected NPN protocol -and `socket.alpnProtocol` is a string containing the selected ALPN -protocol, When both NPN and ALPN extensions are received, ALPN takes -precedence over NPN and the next protocol is selected by ALPN. When -ALPN has no selected protocol, this returns false. + - `isServer`: If `true` - TLS socket will be instantiated in server-mode. + Default: `false` -`socket.servername` is a string containing servername requested with -SNI. + - `server`: An optional [net.Server][] instance + - `requestCert`: Optional, see [tls.createSecurePair][] -### Event: 'clientError' + - `rejectUnauthorized`: Optional, see [tls.createSecurePair][] -`function (exception, tlsSocket) { }` + - `NPNProtocols`: Optional, see [tls.createServer][] -When a client connection emits an 'error' event before secure connection is -established - it will be forwarded here. + - `ALPNProtocols`: Optional, see [tls.createServer][] -`tlsSocket` is the [tls.TLSSocket][] that the error originated from. + - `SNICallback`: Optional, see [tls.createServer][] + - `session`: Optional, a `Buffer` instance, containing TLS session -### Event: 'newSession' + - `requestOCSP`: Optional, if `true` - OCSP status request extension would + be added to client hello, and `OCSPResponse` event will be emitted on socket + before establishing secure communication -`function (sessionId, sessionData, callback) { }` +## tls.connect(options[, callback]) +## tls.connect(port[, host][, options][, callback]) -Emitted on creation of TLS session. May be used to store sessions in external -storage. `callback` must be invoked eventually, otherwise no data will be -sent or received from secure connection. +Creates a new client connection to the given `port` and `host` (old API) or +`options.port` and `options.host`. (If `host` is omitted, it defaults to +`localhost`.) `options` should be an object which specifies: -NOTE: adding this event listener will have an effect only on connections -established after addition of event listener. + - `host`: Host the client should connect to + - `port`: Port the client should connect to -### Event: 'resumeSession' + - `socket`: Establish secure connection on a given socket rather than + creating a new socket. If this option is specified, `host` and `port` + are ignored. -`function (sessionId, callback) { }` + - `path`: Creates unix socket connection to path. If this option is + specified, `host` and `port` are ignored. -Emitted when client wants to resume previous TLS session. Event listener may -perform lookup in external storage using given `sessionId`, and invoke -`callback(null, sessionData)` once finished. If session can't be resumed -(i.e. doesn't exist in storage) one may call `callback(null, null)`. Calling -`callback(err)` will terminate incoming connection and destroy socket. + - `pfx`: A string or `Buffer` containing the private key, certificate and + CA certs of the client in PFX or PKCS12 format. -NOTE: adding this event listener will have an effect only on connections -established after addition of event listener. + - `key`: A string or `Buffer` containing the private key of the client in + PEM format. (Could be an array of keys). -Here's an example for using TLS session resumption: + - `passphrase`: A string of passphrase for the private key or pfx. - var tlsSessionStore = {}; - server.on('newSession', function(id, data, cb) { - tlsSessionStore[id.toString('hex')] = data; - cb(); - }); - server.on('resumeSession', function(id, cb) { - cb(null, tlsSessionStore[id.toString('hex')] || null); - }); + - `cert`: A string or `Buffer` containing the certificate key of the client in + PEM format. (Could be an array of certs). -### Event: 'OCSPRequest' + - `ca`: An array of strings or `Buffer`s of trusted certificates in PEM + format. If this is omitted several well known "root" CAs will be used, + like VeriSign. These are used to authorize connections. -`function (certificate, issuer, callback) { }` + - `ciphers`: A string describing the ciphers to use or exclude, separated by + `:`. Uses the same default cipher suite as `tls.createServer`. -Emitted when the client sends a certificate status request. You could parse -server's current certificate to obtain OCSP url and certificate id, and after -obtaining OCSP response invoke `callback(null, resp)`, where `resp` is a -`Buffer` instance. Both `certificate` and `issuer` are a `Buffer` -DER-representations of the primary and issuer's certificates. They could be used -to obtain OCSP certificate id and OCSP endpoint url. + - `rejectUnauthorized`: If `true`, the server certificate is verified against + the list of supplied CAs. An `'error'` event is emitted if verification + fails; `err.code` contains the OpenSSL error code. Default: `true`. -Alternatively, `callback(null, null)` could be called, meaning that there is no -OCSP response. + - `NPNProtocols`: An array of strings or `Buffer`s containing supported NPN + protocols. `Buffer`s should have the following format: + `0x05hello0x05world`, where first byte is next protocol name's + length. (Passing array should usually be much simpler: + `['hello', 'world']`.) -Calling `callback(err)` will result in a `socket.destroy(err)` call. + - `ALPNProtocols`: An array of strings or `Buffer`s containing + supported ALPN protocols. `Buffer`s should have following format: + `0x05hello0x05world`, where the first byte is the next protocol + name's length. (Passing array should usually be much simpler: + `['hello', 'world']`.) -Typical flow: + - `servername`: Servername for SNI (Server Name Indication) TLS extension. -1. Client connects to server and sends `OCSPRequest` to it (via status info - extension in ClientHello.) -2. Server receives request and invokes `OCSPRequest` event listener if present -3. Server grabs OCSP url from either `certificate` or `issuer` and performs an - [OCSP request] to the CA -4. Server receives `OCSPResponse` from CA and sends it back to client via - `callback` argument -5. Client validates the response and either destroys socket or performs a - handshake. + - `checkServerIdentity(servername, cert)`: Provide an override for checking + server's hostname against the certificate. Should return an error if verification + fails. Return `undefined` if passing. -NOTE: `issuer` could be null, if the certificate is self-signed or if the issuer -is not in the root certificates list. (You could provide an issuer via `ca` -option.) + - `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force + SSL version 3. The possible values depend on your installation of + OpenSSL and are defined in the constant [SSL_METHODS][]. -NOTE: adding this event listener will have an effect only on connections -established after addition of event listener. + - `session`: A `Buffer` instance, containing TLS session. -NOTE: you may want to use some npm module like [asn1.js] to parse the -certificates. + - `minDHSize`: Minimum size of DH parameter in bits to accept a TLS + connection. When a server offers DH parameter with a size less + than this, the TLS connection is destroyed and throws an + error. Default: 1024. +The `callback` parameter will be added as a listener for the +['secureConnect'][] event. -### server.listen(port[, hostname][, callback]) +`tls.connect()` returns a [tls.TLSSocket][] object. -Begin accepting connections on the specified `port` and `hostname`. If the -`hostname` is omitted, the server will accept connections on any IPv6 address -(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A -port value of zero will assign a random port. +Here is an example of a client of echo server as described previously: -This function is asynchronous. The last parameter `callback` will be called -when the server has been bound. + var tls = require('tls'); + var fs = require('fs'); -See `net.Server` for more information. + var options = { + // These are necessary only if using the client certificate authentication + key: fs.readFileSync('client-key.pem'), + cert: fs.readFileSync('client-cert.pem'), + // This is necessary only if the server uses the self-signed certificate + ca: [ fs.readFileSync('server-cert.pem') ] + }; -### server.close([callback]) + var socket = tls.connect(8000, options, function() { + console.log('client connected', + socket.authorized ? 'authorized' : 'unauthorized'); + process.stdin.pipe(socket); + process.stdin.resume(); + }); + socket.setEncoding('utf8'); + socket.on('data', function(data) { + console.log(data); + }); + socket.on('end', function() { + server.close(); + }); -Stops the server from accepting new connections. This function is -asynchronous, the server is finally closed when the server emits a `'close'` -event. Optionally, you can pass a callback to listen for the `'close'` event. - -### server.address() - -Returns the bound address, the address family name and port of the -server as reported by the operating system. See [net.Server.address()][] for -more information. - -### server.getTicketKeys() - -Returns `Buffer` instance holding the keys currently used for -encryption/decryption of the [TLS Session Tickets][] - -### server.setTicketKeys(keys) - -Updates the keys for encryption/decryption of the [TLS Session Tickets][]. +Or -NOTE: the buffer should be 48 bytes long. See server `ticketKeys` option for -more information oh how it is going to be used. + var tls = require('tls'); + var fs = require('fs'); -NOTE: the change is effective only for the future server connections. Existing -or currently pending server connections will use previous keys. + var options = { + pfx: fs.readFileSync('client.pfx') + }; -### server.addContext(hostname, context) + var socket = tls.connect(8000, options, function() { + console.log('client connected', + socket.authorized ? 'authorized' : 'unauthorized'); + process.stdin.pipe(socket); + process.stdin.resume(); + }); + socket.setEncoding('utf8'); + socket.on('data', function(data) { + console.log(data); + }); + socket.on('end', function() { + server.close(); + }); -Add secure context that will be used if client request's SNI hostname is -matching passed `hostname` (wildcards can be used). `context` can contain -`key`, `cert`, `ca` and/or any other properties from `tls.createSecureContext` -`options` argument. +## tls.createSecureContext(details) -### server.maxConnections +Creates a credentials object, with the optional details being a +dictionary with keys: -Set this property to reject connections when the server's connection count -gets high. +* `pfx` : A string or buffer holding the PFX or PKCS12 encoded private + key, certificate and CA certificates +* `key`: A string or `Buffer` containing the private key of the server in + PEM format. To support multiple keys using different algorithms, an array + can be provided. It can either be a plain array of keys, or an array of + objects in the format `{pem: key, passphrase: passphrase}`. (Required) +* `passphrase` : A string of passphrase for the private key or pfx +* `cert` : A string holding the PEM encoded certificate +* `ca` : Either a string or list of strings of PEM encoded CA + certificates to trust. +* `crl` : Either a string or list of strings of PEM encoded CRLs + (Certificate Revocation List) +* `ciphers`: A string describing the ciphers to use or exclude. + Consult + + for details on the format. +* `honorCipherOrder` : When choosing a cipher, use the server's preferences + instead of the client preferences. For further details see `tls` module + documentation. -### server.connections +If no 'ca' details are given, then Node.js will use the default +publicly trusted list of CAs as given in +. -The number of concurrent connections on the server. +## tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options]) -## Class: CryptoStream +Creates a new secure pair object with two streams, one of which reads/writes +encrypted data, and one reads/writes cleartext data. +Generally the encrypted one is piped to/from an incoming encrypted data stream, +and the cleartext one is used as a replacement for the initial encrypted stream. - Stability: 0 - Deprecated: Use [tls.TLSSocket][] instead. + - `credentials`: A secure context object from tls.createSecureContext( ... ) -This is an encrypted stream. + - `isServer`: A boolean indicating whether this tls connection should be + opened as a server or a client. -### cryptoStream.bytesWritten + - `requestCert`: A boolean indicating whether a server should request a + certificate from a connecting client. Only applies to server connections. -A proxy to the underlying socket's bytesWritten accessor, this will return -the total bytes written to the socket, *including the TLS overhead*. + - `rejectUnauthorized`: A boolean indicating whether a server should + automatically reject clients with invalid certificates. Only applies to + servers with `requestCert` enabled. -## Class: tls.TLSSocket + - `options`: An object with common SSL options. See [tls.TLSSocket][]. -This is a wrapped version of [net.Socket][] that does transparent encryption -of written data and all required TLS negotiation. +`tls.createSecurePair()` returns a SecurePair object with `cleartext` and +`encrypted` stream properties. -This instance implements a duplex [Stream][] interfaces. It has all the -common stream methods and events. +NOTE: `cleartext` has the same APIs as [tls.TLSSocket][] -### Event: 'secureConnect' +## tls.createServer(options[, secureConnectionListener]) -This event is emitted after a new connection has been successfully handshaked. -The listener will be called no matter if the server's certificate was -authorized or not. It is up to the user to test `tlsSocket.authorized` -to see if the server certificate was signed by one of the specified CAs. -If `tlsSocket.authorized === false` then the error can be found in -`tlsSocket.authorizationError`. Also if ALPN or NPN was used - you can -check `tlsSocket.alpnProtocol` or `tlsSocket.npnProtocol` for the -negotiated protocol. +Creates a new [tls.Server][]. The `connectionListener` argument is +automatically set as a listener for the [secureConnection][] event. The +`options` object has these possibilities: -### Event: 'OCSPResponse' + - `pfx`: A string or `Buffer` containing the private key, certificate and + CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with + the `key`, `cert` and `ca` options.) -`function (response) { }` + - `key`: A string or `Buffer` containing the private key of the server in + PEM format. To support multiple keys using different algorithms, an array + can be provided. It can either be a plain array of keys, or an array of + objects in the format `{pem: key, passphrase: passphrase}`. (Required) -This event will be emitted if `requestOCSP` option was set. `response` is a -buffer object, containing server's OCSP response. + - `passphrase`: A string of passphrase for the private key or pfx. -Traditionally, the `response` is a signed object from the server's CA that -contains information about server's certificate revocation status. + - `cert`: A string or `Buffer` containing the certificate key of the server in + PEM format. (Could be an array of certs). (Required) -### tlsSocket.encrypted + - `ca`: An array of strings or `Buffer`s of trusted certificates in PEM + format. If this is omitted several well known "root" CAs will be used, + like VeriSign. These are used to authorize connections. -Static boolean value, always `true`. May be used to distinguish TLS sockets -from regular ones. + - `crl` : Either a string or list of strings of PEM encoded CRLs (Certificate + Revocation List) -### tlsSocket.authorized + - `ciphers`: A string describing the ciphers to use or exclude, separated by + `:`. The default cipher suite is: -A boolean that is `true` if the peer certificate was signed by one of the -specified CAs, otherwise `false` + ECDHE-RSA-AES128-GCM-SHA256: + ECDHE-ECDSA-AES128-GCM-SHA256: + ECDHE-RSA-AES256-GCM-SHA384: + ECDHE-ECDSA-AES256-GCM-SHA384: + DHE-RSA-AES128-GCM-SHA256: + ECDHE-RSA-AES128-SHA256: + DHE-RSA-AES128-SHA256: + ECDHE-RSA-AES256-SHA384: + DHE-RSA-AES256-SHA384: + ECDHE-RSA-AES256-SHA256: + DHE-RSA-AES256-SHA256: + HIGH: + !aNULL: + !eNULL: + !EXPORT: + !DES: + !RC4: + !MD5: + !PSK: + !SRP: + !CAMELLIA -### tlsSocket.authorizationError + The default cipher suite prefers GCM ciphers for [Chrome's 'modern + cryptography' setting] and also prefers ECDHE and DHE ciphers for Perfect + Forward secrecy, while offering *some* backward compatibiltity. -The reason why the peer's certificate has not been verified. This property -becomes available only when `tlsSocket.authorized === false`. + 128 bit AES is preferred over 192 and 256 bit AES in light of [specific + attacks affecting larger AES key sizes]. -### tlsSocket.getPeerCertificate([ detailed ]) + Old clients that rely on insecure and deprecated RC4 or DES-based ciphers + (like Internet Explorer 6) aren't able to complete the handshake with the default + configuration. If you absolutely must support these clients, the + [TLS recommendations] may offer a compatible cipher suite. For more details + on the format, see the [OpenSSL cipher list format documentation]. -Returns an object representing the peer's certificate. The returned object has -some properties corresponding to the field of the certificate. If `detailed` -argument is `true` - the full chain with `issuer` property will be returned, -if `false` - only the top certificate without `issuer` property. + - `ecdhCurve`: A string describing a named curve to use for ECDH key agreement + or false to disable ECDH. -Example: + Defaults to `prime256v1` (NIST P-256). Use [crypto.getCurves()][] to obtain + a list of available curve names. On recent releases, + `openssl ecparam -list_curves` will also display the name and description of + each available elliptic curve. - { subject: - { C: 'UK', - ST: 'Acknack Ltd', - L: 'Rhys Jones', - O: 'node.js', - OU: 'Test TLS Certificate', - CN: 'localhost' }, - issuerInfo: - { C: 'UK', - ST: 'Acknack Ltd', - L: 'Rhys Jones', - O: 'node.js', - OU: 'Test TLS Certificate', - CN: 'localhost' }, - issuer: - { ... another certificate ... }, - raw: < RAW DER buffer >, - valid_from: 'Nov 11 09:52:22 2009 GMT', - valid_to: 'Nov 6 09:52:22 2029 GMT', - fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF', - serialNumber: 'B9B0D332A1AA5635' } + - `dhparam`: A string or `Buffer` containing Diffie Hellman parameters, + required for Perfect Forward Secrecy. Use `openssl dhparam` to create it. + Its key length should be greater than or equal to 1024 bits, otherwise + it throws an error. It is strongly recommended to use 2048 bits or + more for stronger security. If omitted or invalid, it is silently + discarded and DHE ciphers won't be available. -If the peer does not provide a certificate, it returns `null` or an empty -object. + - `handshakeTimeout`: Abort the connection if the SSL/TLS handshake does not + finish in this many milliseconds. The default is 120 seconds. -### tlsSocket.getCipher() -Returns an object representing the cipher name and the SSL/TLS -protocol version of the current connection. + A `'clientError'` is emitted on the `tls.Server` object whenever a handshake + times out. -Example: -{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' } + - `honorCipherOrder` : When choosing a cipher, use the server's preferences + instead of the client preferences. Default: `true`. -See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in -http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more -information. + - `requestCert`: If `true` the server will request a certificate from + clients that connect and attempt to verify that certificate. Default: + `false`. -### tlsSocket.getEphemeralKeyInfo() + - `rejectUnauthorized`: If `true` the server will reject any connection + which is not authorized with the list of supplied CAs. This option only + has an effect if `requestCert` is `true`. Default: `false`. -Returns an object representing a type, name and size of parameter of -an ephemeral key exchange in [Perfect forward Secrecy][] on a client -connection. It returns an empty object when the key exchange is not -ephemeral. As it is only supported on a client socket, it returns null -if this is called on a server socket. The supported types are 'DH' and -'ECDH'. The `name` property is only available in 'ECDH'. + - `NPNProtocols`: An array or `Buffer` of possible NPN protocols. (Protocols + should be ordered by their priority). -Example: + - `ALPNProtocols`: An array or `Buffer` of possible ALPN + protocols. (Protocols should be ordered by their priority). When + the server receives both NPN and ALPN extensions from the client, + ALPN takes precedence over NPN and the server does not send an NPN + extension to the client. - { type: 'ECDH', name: 'prime256v1', size: 256 } + - `SNICallback(servername, cb)`: A function that will be called if client + supports SNI TLS extension. Two argument will be passed to it: `servername`, + and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a + SecureContext instance. + (You can use `tls.createSecureContext(...)` to get proper + SecureContext). If `SNICallback` wasn't provided - default callback with + high-level API will be used (see below). -### tlsSocket.renegotiate(options, callback) + - `sessionTimeout`: An integer specifying the seconds after which TLS + session identifiers and TLS session tickets created by the server are + timed out. See [SSL_CTX_set_timeout] for more details. -Initiate TLS renegotiation process. The `options` may contain the following -fields: `rejectUnauthorized`, `requestCert` (See [tls.createServer][] -for details). `callback(err)` will be executed with `null` as `err`, -once the renegotiation is successfully completed. + - `ticketKeys`: A 48-byte `Buffer` instance consisting of 16-byte prefix, + 16-byte hmac key, 16-byte AES key. You could use it to accept tls session + tickets on multiple instances of tls server. -NOTE: Can be used to request peer's certificate after the secure connection -has been established. + NOTE: Automatically shared between `cluster` module workers. -ANOTHER NOTE: When running as the server, socket will be destroyed -with an error after `handshakeTimeout` timeout. + - `sessionIdContext`: A string containing an opaque identifier for session + resumption. If `requestCert` is `true`, the default is MD5 hash value + generated from command-line. Otherwise, the default is not provided. -### tlsSocket.setMaxSendFragment(size) + - `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force + SSL version 3. The possible values depend on your installation of + OpenSSL and are defined in the constant [SSL_METHODS][]. -Set maximum TLS fragment size (default and maximum value is: `16384`, minimum -is: `512`). Returns `true` on success, `false` otherwise. +Here is a simple example echo server: -Smaller fragment size decreases buffering latency on the client: large -fragments are buffered by the TLS layer until the entire fragment is received -and its integrity is verified; large fragments can span multiple roundtrips, -and their processing can be delayed due to packet loss or reordering. However, -smaller fragments add extra TLS framing bytes and CPU overhead, which may -decrease overall server throughput. + var tls = require('tls'); + var fs = require('fs'); -### tlsSocket.getSession() + var options = { + key: fs.readFileSync('server-key.pem'), + cert: fs.readFileSync('server-cert.pem'), -Return ASN.1 encoded TLS session or `undefined` if none was negotiated. Could -be used to speed up handshake establishment when reconnecting to the server. + // This is necessary only if using the client certificate authentication. + requestCert: true, -### tlsSocket.getTLSTicket() + // This is necessary only if the client uses the self-signed certificate. + ca: [ fs.readFileSync('client-cert.pem') ] + }; -NOTE: Works only with client TLS sockets. Useful only for debugging, for -session reuse provide `session` option to `tls.connect`. + var server = tls.createServer(options, function(socket) { + console.log('server connected', + socket.authorized ? 'authorized' : 'unauthorized'); + socket.write("welcome!\n"); + socket.setEncoding('utf8'); + socket.pipe(socket); + }); + server.listen(8000, function() { + console.log('server bound'); + }); -Return TLS session ticket or `undefined` if none was negotiated. +Or -### tlsSocket.address() + var tls = require('tls'); + var fs = require('fs'); -Returns the bound address, the address family name and port of the -underlying socket as reported by the operating system. Returns an -object with three properties, e.g. -`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + var options = { + pfx: fs.readFileSync('server.pfx'), -### tlsSocket.remoteAddress + // This is necessary only if using the client certificate authentication. + requestCert: true, -The string representation of the remote IP address. For example, -`'74.125.127.100'` or `'2001:4860:a005::68'`. + }; -### tlsSocket.remoteFamily + var server = tls.createServer(options, function(socket) { + console.log('server connected', + socket.authorized ? 'authorized' : 'unauthorized'); + socket.write("welcome!\n"); + socket.setEncoding('utf8'); + socket.pipe(socket); + }); + server.listen(8000, function() { + console.log('server bound'); + }); +You can test this server by connecting to it with `openssl s_client`: -The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. -### tlsSocket.remotePort + openssl s_client -connect 127.0.0.1:8000 -The numeric representation of the remote port. For example, `443`. -### tlsSocket.localAddress +## tls.getCiphers() -The string representation of the local IP address. +Returns an array with the names of the supported SSL ciphers. -### tlsSocket.localPort +Example: -The numeric representation of the local port. + var ciphers = tls.getCiphers(); + console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...] [OpenSSL cipher list format documentation]: http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT [Chrome's 'modern cryptography' setting]: http://www.chromium.org/Home/chromium-security/education/tls#TOC-Deprecation-of-TLS-Features-Algorithms-in-Chrome