diff --git a/doc/api/assert.markdown b/doc/api/assert.markdown index 7bf6ebb40fd30a..fbc5aef862477c 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(true, !!value, 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. 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 diff --git a/doc/api/child_process.markdown b/doc/api/child_process.markdown index 13997d65452909..b17832ed793756 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} @@ -339,23 +278,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]) @@ -451,6 +573,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: @@ -504,166 +662,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, @@ -673,15 +673,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).) @@ -690,21 +692,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 @@ -739,17 +742,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).) @@ -758,18 +759,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 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]; + }); diff --git a/doc/api/console.markdown b/doc/api/console.markdown index 4b5ed61b199e09..fb4c76b01cd02d 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(label) Used to calculate the duration of a specific operation. To start a timer, call @@ -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`. diff --git a/doc/api/dns.markdown b/doc/api/dns.markdown index a945a7d90882d2..13ef976fef0251 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