mirror of
https://github.com/nodejs/node.git
synced 2026-11-24 21:50:36 -05:00
Merge branch 'json-api-docs'
This commit is contained in:
commit
0e7dad3f6e
58 files changed
+3150
-2249
No files matched your search
@@ -92,7 +92,8 @@ test-npm-publish: node
|
||||
npm_package_config_publishtest=true ./node deps/npm/test/run.js
|
||||
|
||||
apidoc_sources = $(wildcard doc/api/*.markdown)
|
||||
apidocs = $(addprefix out/,$(apidoc_sources:.markdown=.html))
|
||||
apidocs = $(addprefix out/,$(apidoc_sources:.markdown=.html)) \
|
||||
$(addprefix out/,$(apidoc_sources:.markdown=.json))
|
||||
|
||||
apidoc_dirs = out/doc out/doc/api/ out/doc/api/assets out/doc/about out/doc/community out/doc/logos out/doc/images
|
||||
|
||||
@@ -115,7 +116,7 @@ website_files = \
|
||||
out/doc/logos/index.html \
|
||||
$(doc_images)
|
||||
|
||||
doc: node $(apidoc_dirs) $(website_files) $(apiassets) $(apidocs)
|
||||
doc: node $(apidoc_dirs) $(website_files) $(apiassets) $(apidocs) tools/doc/
|
||||
|
||||
$(apidoc_dirs):
|
||||
mkdir -p $@
|
||||
@@ -126,8 +127,11 @@ out/doc/api/assets/%: doc/api_assets/% out/doc/api/assets/
|
||||
out/doc/%: doc/%
|
||||
cp -r $< $@
|
||||
|
||||
out/doc/api/%.html: doc/api/%.markdown node $(apidoc_dirs) $(apiassets) tools/doctool/doctool.js
|
||||
out/Release/node tools/doctool/doctool.js doc/template.html $< > $@
|
||||
out/doc/api/%.json: doc/api/%.markdown
|
||||
out/Release/node tools/doc/generate.js --format=json $< > $@
|
||||
|
||||
out/doc/api/%.html: doc/api/%.markdown
|
||||
out/Release/node tools/doc/generate.js --format=html --template=doc/template.html $< > $@
|
||||
|
||||
website-upload: doc
|
||||
rsync -r out/doc/ node@nodejs.org:~/web/nodejs.org/
|
||||
|
||||
@@ -102,7 +102,7 @@ console.log('Server running at http://127.0.0.1:1337/');</pre>
|
||||
<p>But what about multiple-processor concurrency? Aren't
|
||||
threads necessary to scale programs to multi-core computers?
|
||||
You can start new processes via <code><a
|
||||
href="http://nodejs.org/docs/latest/api/child_processes.html#child_process.fork">child_process.fork()</a></code>
|
||||
href="http://nodejs.org/docs/latest/api/child_process.html#child_process.fork">child_process.fork()</a></code>
|
||||
these other processes will be scheduled in parallel. For load
|
||||
balancing incoming connections across multiple processes use
|
||||
<a href="http://nodejs.org/docs/latest/api/cluster.html">the
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
## Table of Contents
|
||||
|
||||
* [About these Docs](documentation.html)
|
||||
* [Synopsis](synopsis.html)
|
||||
* [Globals](globals.html)
|
||||
* [STDIO](stdio.html)
|
||||
@@ -9,8 +8,8 @@
|
||||
* [Process](process.html)
|
||||
* [Utilities](util.html)
|
||||
* [Events](events.html)
|
||||
* [Buffers](buffers.html)
|
||||
* [Streams](streams.html)
|
||||
* [Buffer](buffer.html)
|
||||
* [Stream](stream.html)
|
||||
* [Crypto](crypto.html)
|
||||
* [TLS/SSL](tls.html)
|
||||
* [String Decoder](string_decoder.html)
|
||||
@@ -26,7 +25,7 @@
|
||||
* [Readline](readline.html)
|
||||
* [REPL](repl.html)
|
||||
* [VM](vm.html)
|
||||
* [Child Processes](child_processes.html)
|
||||
* [Child Processes](child_process.html)
|
||||
* [Assertion Testing](assert.html)
|
||||
* [TTY](tty.html)
|
||||
* [ZLIB](zlib.html)
|
||||
@@ -35,4 +34,3 @@
|
||||
* [Cluster](cluster.html)
|
||||
* Appendixes
|
||||
* [Appendix 1: Recommended Third-party Modules](appendix_1.html)
|
||||
* [Appendix 2: Deprecated API's](appendix_2.html)
|
||||
@@ -1,4 +1,4 @@
|
||||
## Addons
|
||||
# Addons
|
||||
|
||||
Addons are dynamically linked shared objects. They can provide glue to C and
|
||||
C++ libraries. The API (at the moment) is rather complex, involving
|
||||
@@ -24,7 +24,7 @@ compiling your module, you don't need to worry about linking to any of these
|
||||
libraries.
|
||||
|
||||
|
||||
### Hello world
|
||||
## Hello world
|
||||
|
||||
To get started let's make a small Addon which is the C++ equivalent of
|
||||
the following Javascript code:
|
||||
@@ -129,7 +129,7 @@ In cases where there is more than one `.cc` file, simply add the file name to th
|
||||
obj.source = ['addon.cc', 'myexample.cc']
|
||||
|
||||
|
||||
#### Function arguments
|
||||
### Function arguments
|
||||
|
||||
The following pattern illustrates how to read arguments from JavaScript
|
||||
function calls and return a result. This is the main and only needed source
|
||||
@@ -172,7 +172,7 @@ You can test it with the following JavaScript snippet:
|
||||
console.log( 'This should be eight:', addon.add(3,5) );
|
||||
|
||||
|
||||
#### Callbacks
|
||||
### Callbacks
|
||||
|
||||
You can pass JavaScript functions to a C++ function and execute them from
|
||||
there. Here's `addon.cc`:
|
||||
@@ -209,7 +209,7 @@ To test it run the following JavaScript snippet:
|
||||
});
|
||||
|
||||
|
||||
#### Object factory
|
||||
### Object factory
|
||||
|
||||
You can create and return new objects from within a C++ function with this
|
||||
`addon.cc` pattern, which returns an object with property `msg` that echoes
|
||||
@@ -245,7 +245,7 @@ To test it in JavaScript:
|
||||
console.log(obj1.msg+' '+obj2.msg); // 'hello world'
|
||||
|
||||
|
||||
#### Function factory
|
||||
### Function factory
|
||||
|
||||
This pattern illustrates how to create and return a JavaScript function that
|
||||
wraps a C++ function:
|
||||
@@ -286,7 +286,7 @@ To test:
|
||||
console.log(fn()); // 'hello world'
|
||||
|
||||
|
||||
#### Wrapping C++ objects
|
||||
### Wrapping C++ objects
|
||||
|
||||
Here we will create a wrapper for a C++ object/class `MyObject` that can be
|
||||
instantiated in JavaScript through the `new` operator. First prepare the main
|
||||
@@ -381,7 +381,7 @@ Test it with:
|
||||
console.log( obj.plusOne() ); // 13
|
||||
|
||||
|
||||
#### Factory of wrapped objects
|
||||
### Factory of wrapped objects
|
||||
|
||||
This is useful when you want to be able to create native objects without
|
||||
explicitly instantiating them with the `new` operator in JavaScript, e.g.
|
||||
@@ -507,7 +507,7 @@ Test it with:
|
||||
console.log( obj2.plusOne() ); // 23
|
||||
|
||||
|
||||
#### Passing wrapped objects around
|
||||
### Passing wrapped objects around
|
||||
|
||||
In addition to wrapping and returning C++ objects, you can pass them around
|
||||
by unwrapping them with Node's `node::ObjectWrap::Unwrap` helper function.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
@include documentation
|
||||
@include synopsis
|
||||
@include globals
|
||||
@include stdio
|
||||
@@ -5,12 +6,10 @@
|
||||
@include modules
|
||||
@include addons
|
||||
@include process
|
||||
@include constants
|
||||
@include util
|
||||
@include freelist
|
||||
@include events
|
||||
@include buffers
|
||||
@include streams
|
||||
@include buffer
|
||||
@include stream
|
||||
@include crypto
|
||||
@include tls
|
||||
@include string_decoder
|
||||
@@ -26,14 +25,11 @@
|
||||
@include readline
|
||||
@include repl
|
||||
@include vm
|
||||
@include child_processes
|
||||
@include child_process
|
||||
@include assert
|
||||
@include tty
|
||||
@include zlib
|
||||
@include os
|
||||
@include debugger
|
||||
@include cluster
|
||||
|
||||
# Appendixes
|
||||
@include appendix_1
|
||||
@include appendix_2
|
||||
@@ -1,4 +1,4 @@
|
||||
## Appendix 1 - Third Party Modules
|
||||
# Appendix 1 - Third Party Modules
|
||||
|
||||
There are many third party modules for Node. At the time of writing, August
|
||||
2010, the master repository of modules is
|
||||
|
||||
Whitespace-only changes.
+12
-12
@@ -1,41 +1,41 @@
|
||||
## Assert
|
||||
# Assert
|
||||
|
||||
This module is used for writing unit tests for your applications, you can
|
||||
access it with `require('assert')`.
|
||||
|
||||
### assert.fail(actual, expected, message, operator)
|
||||
## 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])
|
||||
## assert(value, message), assert.ok(value, [message])
|
||||
|
||||
Tests if value is a `true` value, it is equivalent to `assert.equal(true, value, message);`
|
||||
|
||||
### assert.equal(actual, expected, [message])
|
||||
## assert.equal(actual, expected, [message])
|
||||
|
||||
Tests shallow, coercive equality with the equal comparison operator ( `==` ).
|
||||
|
||||
### assert.notEqual(actual, expected, [message])
|
||||
## assert.notEqual(actual, expected, [message])
|
||||
|
||||
Tests shallow, coercive non-equality with the not equal comparison operator ( `!=` ).
|
||||
|
||||
### assert.deepEqual(actual, expected, [message])
|
||||
## assert.deepEqual(actual, expected, [message])
|
||||
|
||||
Tests for deep equality.
|
||||
|
||||
### assert.notDeepEqual(actual, expected, [message])
|
||||
## assert.notDeepEqual(actual, expected, [message])
|
||||
|
||||
Tests for any deep inequality.
|
||||
|
||||
### assert.strictEqual(actual, expected, [message])
|
||||
## assert.strictEqual(actual, expected, [message])
|
||||
|
||||
Tests strict equality, as determined by the strict equality operator ( `===` )
|
||||
|
||||
### assert.notStrictEqual(actual, expected, [message])
|
||||
## assert.notStrictEqual(actual, expected, [message])
|
||||
|
||||
Tests strict non-equality, as determined by the strict not equal operator ( `!==` )
|
||||
|
||||
### assert.throws(block, [error], [message])
|
||||
## assert.throws(block, [error], [message])
|
||||
|
||||
Expects `block` to throw an error. `error` can be constructor, regexp or
|
||||
validation function.
|
||||
@@ -72,11 +72,11 @@ Custom error validation:
|
||||
"unexpected error"
|
||||
);
|
||||
|
||||
### assert.doesNotThrow(block, [error], [message])
|
||||
## assert.doesNotThrow(block, [error], [message])
|
||||
|
||||
Expects `block` not to throw an error, see assert.throws for details.
|
||||
|
||||
### assert.ifError(value)
|
||||
## assert.ifError(value)
|
||||
|
||||
Tests if value is not a false value, throws if it is a true value. Useful when
|
||||
testing the first argument, `error` in callbacks.
|
||||
@@ -1,4 +1,6 @@
|
||||
## Buffers
|
||||
# Buffer
|
||||
|
||||
Stability: 3 - Stable
|
||||
|
||||
Pure Javascript is Unicode friendly but not nice to binary data. When
|
||||
dealing with TCP streams or the file system, it's necessary to handle octet
|
||||
@@ -9,46 +11,63 @@ Raw data is stored in instances of the `Buffer` class. A `Buffer` is similar
|
||||
to an array of integers but corresponds to a raw memory allocation outside
|
||||
the V8 heap. A `Buffer` cannot be resized.
|
||||
|
||||
The `Buffer` object is global.
|
||||
The `Buffer` class is a global, making it very rare that one would need
|
||||
to ever `require('buffer')`.
|
||||
|
||||
Converting between Buffers and JavaScript string objects requires an explicit encoding
|
||||
method. Here are the different string encodings;
|
||||
Converting between Buffers and JavaScript string objects requires an explicit
|
||||
encoding method. Here are the different string encodings.
|
||||
|
||||
* `'ascii'` - for 7 bit ASCII data only. This encoding method is very fast, and will
|
||||
strip the high bit if set.
|
||||
Note that this encoding converts a null character (`'\0'` or `'\u0000'`) into
|
||||
`0x20` (character code of a space). If you want to convert a null character
|
||||
into `0x00`, you should use `'utf8'`.
|
||||
* `'ascii'` - for 7 bit ASCII data only. This encoding method is very fast, and
|
||||
will strip the high bit if set.
|
||||
Note that this encoding converts a null character (`'\0'` or `'\u0000'`) into
|
||||
`0x20` (character code of a space). If you want to convert a null character
|
||||
into `0x00`, you should use `'utf8'`.
|
||||
|
||||
* `'utf8'` - Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.
|
||||
|
||||
* `'ucs2'` - 2-bytes, little endian encoded Unicode characters. It can encode
|
||||
only BMP(Basic Multilingual Plane, U+0000 - U+FFFF).
|
||||
only BMP(Basic Multilingual Plane, U+0000 - U+FFFF).
|
||||
|
||||
* `'base64'` - Base64 string encoding.
|
||||
|
||||
* `'binary'` - A way of encoding raw binary data into strings by using only
|
||||
the first 8 bits of each character. This encoding method is deprecated and
|
||||
should be avoided in favor of `Buffer` objects where possible. This encoding
|
||||
will be removed in future versions of Node.
|
||||
the first 8 bits of each character. This encoding method is deprecated and
|
||||
should be avoided in favor of `Buffer` objects where possible. This encoding
|
||||
will be removed in future versions of Node.
|
||||
|
||||
* `'hex'` - Encode each byte as two hexidecimal characters.
|
||||
|
||||
## Class: Buffer
|
||||
|
||||
The Buffer class is a global type for dealing with binary data directly.
|
||||
It can be constructed in a variety of ways.
|
||||
|
||||
### new Buffer(size)
|
||||
|
||||
* `size` Number
|
||||
|
||||
Allocates a new buffer of `size` octets.
|
||||
|
||||
### new Buffer(array)
|
||||
|
||||
* `array` Array
|
||||
|
||||
Allocates a new buffer using an `array` of octets.
|
||||
|
||||
### new Buffer(str, [encoding])
|
||||
|
||||
* `str` String - string to encode.
|
||||
* `encoding` String - encoding to use, Optional.
|
||||
|
||||
Allocates a new buffer containing the given `str`.
|
||||
`encoding` defaults to `'utf8'`.
|
||||
|
||||
### buffer.write(string, [offset], [length], [encoding])
|
||||
### buf.write(string, [offset], [length], [encoding])
|
||||
|
||||
* `string` String - data to be written to buffer
|
||||
* `offset` Number, Optional, Default: 0
|
||||
* `length` Number, Optional
|
||||
* `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
|
||||
@@ -66,7 +85,11 @@ bytes written) is set in `Buffer._charsWritten` and will be overwritten the
|
||||
next time `buf.write()` is called.
|
||||
|
||||
|
||||
### buffer.toString(encoding, [start], [end])
|
||||
### buf.toString([encoding], [start], [end])
|
||||
|
||||
* `encoding` String, Optional, Default: 'utf8'
|
||||
* `start` Number, Optional, Default: 0
|
||||
* `end` Number, Optional
|
||||
|
||||
Decodes and returns a string from buffer data encoded with `encoding`
|
||||
(defaults to `'utf8'`) beginning at `start` (defaults to `0`) and ending at
|
||||
@@ -75,7 +98,10 @@ Decodes and returns a string from buffer data encoded with `encoding`
|
||||
See `buffer.write()` example, above.
|
||||
|
||||
|
||||
### buffer[index]
|
||||
### buf[index]
|
||||
|
||||
<!--type=property-->
|
||||
<!--name=[index]-->
|
||||
|
||||
Get and set the octet at `index`. The values refer to individual bytes,
|
||||
so the legal range is between `0x00` and `0xFF` hex or `0` and `255`.
|
||||
@@ -93,11 +119,18 @@ Example: copy an ASCII string into a buffer, one byte at a time:
|
||||
|
||||
// node.js
|
||||
|
||||
### Buffer.isBuffer(obj)
|
||||
### Class Method: Buffer.isBuffer(obj)
|
||||
|
||||
* `obj` Object
|
||||
* Return: Boolean
|
||||
|
||||
Tests if `obj` is a `Buffer`.
|
||||
|
||||
### Buffer.byteLength(string, [encoding])
|
||||
### Class Method: Buffer.byteLength(string, [encoding])
|
||||
|
||||
* `string` String
|
||||
* `encoding` String, Optional, Default: 'utf8'
|
||||
* Return: Number
|
||||
|
||||
Gives the actual byte length of a string. `encoding` defaults to `'utf8'`.
|
||||
This is not the same as `String.prototype.length` since that returns the
|
||||
@@ -112,8 +145,9 @@ Example:
|
||||
|
||||
// ½ + ¼ = ¾: 9 characters, 12 bytes
|
||||
|
||||
### buf.length
|
||||
|
||||
### buffer.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
|
||||
@@ -128,7 +162,12 @@ buffer object. It does not change when the contents of the buffer are changed.
|
||||
// 1234
|
||||
// 1234
|
||||
|
||||
### buffer.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])
|
||||
### buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])
|
||||
|
||||
* `targetBuffer` Buffer object - Buffer to copy into
|
||||
* `targetStart` Number, Optional, Default: 0
|
||||
* `sourceStart` Number, Optional, Default: 0
|
||||
* `sourceEnd` Number, Optional, Default: 0
|
||||
|
||||
Does copy between buffers. The source and target regions can be overlapped.
|
||||
`targetStart` and `sourceStart` default to `0`.
|
||||
@@ -151,7 +190,10 @@ into `buf2`, starting at the 8th byte in `buf2`.
|
||||
// !!!!!!!!qrst!!!!!!!!!!!!!
|
||||
|
||||
|
||||
### buffer.slice([start], [end])
|
||||
### buf.slice([start], [end])
|
||||
|
||||
* `start` Number, Optional, Default: 0
|
||||
* `end` Number, Optional, Default: 0
|
||||
|
||||
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
|
||||
@@ -176,7 +218,11 @@ byte from the original Buffer.
|
||||
// abc
|
||||
// !bc
|
||||
|
||||
### buffer.readUInt8(offset, [noAssert])
|
||||
### buf.readUInt8(offset, [noAssert])
|
||||
|
||||
* `offset` Number
|
||||
* `noAssert` Boolean, Optional, Default: false
|
||||
* Return: Number
|
||||
|
||||
Reads an unsigned 8 bit integer from the buffer at the specified offset.
|
||||
|
||||
@@ -201,8 +247,12 @@ Example:
|
||||
// 0x23
|
||||
// 0x42
|
||||
|
||||
### buffer.readUInt16LE(offset, [noAssert])
|
||||
### buffer.readUInt16BE(offset, [noAssert])
|
||||
### buf.readUInt16LE(offset, [noAssert])
|
||||
### buf.readUInt16BE(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.
|
||||
@@ -233,8 +283,12 @@ Example:
|
||||
// 0x2342
|
||||
// 0x4223
|
||||
|
||||
### buffer.readUInt32LE(offset, [noAssert])
|
||||
### buffer.readUInt32BE(offset, [noAssert])
|
||||
### buf.readUInt32LE(offset, [noAssert])
|
||||
### buf.readUInt32BE(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.
|
||||
@@ -257,7 +311,11 @@ Example:
|
||||
// 0x03042342
|
||||
// 0x42230403
|
||||
|
||||
### buffer.readInt8(offset, [noAssert])
|
||||
### buf.readInt8(offset, [noAssert])
|
||||
|
||||
* `offset` Number
|
||||
* `noAssert` Boolean, Optional, Default: false
|
||||
* Return: Number
|
||||
|
||||
Reads a signed 8 bit integer from the buffer at the specified offset.
|
||||
|
||||
@@ -267,8 +325,12 @@ 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.
|
||||
|
||||
### buffer.readInt16LE(offset, [noAssert])
|
||||
### buffer.readInt16BE(offset, [noAssert])
|
||||
### buf.readInt16LE(offset, [noAssert])
|
||||
### buf.readInt16BE(offset, [noAssert])
|
||||
|
||||
* `offset` Number
|
||||
* `noAssert` Boolean, Optional, Default: false
|
||||
* Return: Number
|
||||
|
||||
Reads a signed 16 bit integer from the buffer at the specified offset with
|
||||
specified endian format.
|
||||
@@ -279,8 +341,12 @@ 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.
|
||||
|
||||
### buffer.readInt32LE(offset, [noAssert])
|
||||
### buffer.readInt32BE(offset, [noAssert])
|
||||
### buf.readInt32LE(offset, [noAssert])
|
||||
### buf.readInt32BE(offset, [noAssert])
|
||||
|
||||
* `offset` Number
|
||||
* `noAssert` Boolean, Optional, Default: false
|
||||
* Return: Number
|
||||
|
||||
Reads a signed 32 bit integer from the buffer at the specified offset with
|
||||
specified endian format.
|
||||
@@ -291,8 +357,12 @@ 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.
|
||||
|
||||
### buffer.readFloatLE(offset, [noAssert])
|
||||
### buffer.readFloatBE(offset, [noAssert])
|
||||
### buf.readFloatLE(offset, [noAssert])
|
||||
### buf.readFloatBE(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.
|
||||
@@ -313,8 +383,12 @@ Example:
|
||||
|
||||
// 0x01
|
||||
|
||||
### buffer.readDoubleLE(offset, [noAssert])
|
||||
### buffer.readDoubleBE(offset, [noAssert])
|
||||
### buf.readDoubleLE(offset, [noAssert])
|
||||
### buf.readDoubleBE(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.
|
||||
@@ -339,7 +413,11 @@ Example:
|
||||
|
||||
// 0.3333333333333333
|
||||
|
||||
### buffer.writeUInt8(value, offset, [noAssert])
|
||||
### buf.writeUInt8(value, offset, [noAssert])
|
||||
|
||||
* `value` Number
|
||||
* `offset` Number
|
||||
* `noAssert` Boolean, Optional, Default: false
|
||||
|
||||
Writes `value` to the buffer at the specified offset. Note, `value` must be a
|
||||
valid unsigned 8 bit integer.
|
||||
@@ -361,8 +439,12 @@ Example:
|
||||
|
||||
// <Buffer 03 04 23 42>
|
||||
|
||||
### buffer.writeUInt16LE(value, offset, [noAssert])
|
||||
### buffer.writeUInt16BE(value, offset, [noAssert])
|
||||
### buf.writeUInt16LE(value, offset, [noAssert])
|
||||
### buf.writeUInt16BE(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.
|
||||
@@ -388,8 +470,12 @@ Example:
|
||||
// <Buffer de ad be ef>
|
||||
// <Buffer ad de ef be>
|
||||
|
||||
### buffer.writeUInt32LE(value, offset, [noAssert])
|
||||
### buffer.writeUInt32BE(value, offset, [noAssert])
|
||||
### buf.writeUInt32LE(value, offset, [noAssert])
|
||||
### buf.writeUInt32BE(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.
|
||||
@@ -413,7 +499,11 @@ Example:
|
||||
// <Buffer fe ed fa ce>
|
||||
// <Buffer ce fa ed fe>
|
||||
|
||||
### buffer.writeInt8(value, offset, [noAssert])
|
||||
### buf.writeInt8(value, offset, [noAssert])
|
||||
|
||||
* `value` Number
|
||||
* `offset` Number
|
||||
* `noAssert` Boolean, Optional, Default: false
|
||||
|
||||
Writes `value` to the buffer at the specified offset. Note, `value` must be a
|
||||
valid signed 8 bit integer.
|
||||
@@ -426,8 +516,12 @@ 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`.
|
||||
|
||||
### buffer.writeInt16LE(value, offset, [noAssert])
|
||||
### buffer.writeInt16BE(value, offset, [noAssert])
|
||||
### buf.writeInt16LE(value, offset, [noAssert])
|
||||
### buf.writeInt16BE(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 signed 16 bit integer.
|
||||
@@ -440,8 +534,12 @@ 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`.
|
||||
|
||||
### buffer.writeInt32LE(value, offset, [noAssert])
|
||||
### buffer.writeInt32BE(value, offset, [noAssert])
|
||||
### buf.writeInt32LE(value, offset, [noAssert])
|
||||
### buf.writeInt32BE(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 signed 32 bit integer.
|
||||
@@ -454,8 +552,12 @@ 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`.
|
||||
|
||||
### buffer.writeFloatLE(value, offset, [noAssert])
|
||||
### buffer.writeFloatBE(value, offset, [noAssert])
|
||||
### buf.writeFloatLE(value, offset, [noAssert])
|
||||
### buf.writeFloatBE(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 32 bit float.
|
||||
@@ -479,8 +581,12 @@ Example:
|
||||
// <Buffer 4f 4a fe bb>
|
||||
// <Buffer bb fe 4a 4f>
|
||||
|
||||
### buffer.writeDoubleLE(value, offset, [noAssert])
|
||||
### buffer.writeDoubleBE(value, offset, [noAssert])
|
||||
### buf.writeDoubleLE(value, offset, [noAssert])
|
||||
### buf.writeDoubleBE(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.
|
||||
@@ -504,7 +610,11 @@ Example:
|
||||
// <Buffer 43 eb d5 b7 dd f9 5f d7>
|
||||
// <Buffer d7 5f f9 dd b7 d5 eb 43>
|
||||
|
||||
### buffer.fill(value, [offset], [end])
|
||||
### buf.fill(value, [offset], [end])
|
||||
|
||||
* `value`
|
||||
* `offset` Number, Optional
|
||||
* `end` Number, Optional
|
||||
|
||||
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
|
||||
@@ -513,7 +623,23 @@ buffer.
|
||||
var b = new Buffer(50);
|
||||
b.fill("h");
|
||||
|
||||
### INSPECT_MAX_BYTES
|
||||
## buffer.INSPECT_MAX_BYTES
|
||||
|
||||
* Number, Default: 50
|
||||
|
||||
How many bytes will be returned when `buffer.inspect()` is called. This can
|
||||
be overridden by user modules.
|
||||
|
||||
Note that this is a property on the buffer module returned by
|
||||
`require('buffer')`, not on the Buffer global, or a buffer instance.
|
||||
|
||||
## Class: SlowBuffer
|
||||
|
||||
This class is primarily for internal use. JavaScript programs should
|
||||
use Buffer instead of using SlowBuffer.
|
||||
|
||||
In order to avoid the overhead of allocating many C++ Buffer objects for
|
||||
small blocks of memory in the lifetime of a server, Node allocates memory
|
||||
in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it
|
||||
will be backed by a parent SlowBuffer object. If it is larger than this,
|
||||
then Node will allocate a SlowBuffer slab for it directly.
|
||||
@@ -1,21 +1,32 @@
|
||||
## Child Processes
|
||||
# Child Process
|
||||
|
||||
Node provides a tri-directional `popen(3)` facility through the `ChildProcess`
|
||||
class.
|
||||
Node provides a tri-directional `popen(3)` facility through the
|
||||
`child_process` module.
|
||||
|
||||
It is possible to stream data through the child's `stdin`, `stdout`, and
|
||||
It is possible to stream data through a child's `stdin`, `stdout`, and
|
||||
`stderr` in a fully non-blocking way.
|
||||
|
||||
To create a child process use `require('child_process').spawn()`.
|
||||
To create a child process use `require('child_process').spawn()` or
|
||||
`require('child_process').fork()`. The semantics of each are slightly
|
||||
different, and explained below.
|
||||
|
||||
Child processes always have three streams associated with them. `child.stdin`,
|
||||
`child.stdout`, and `child.stderr`.
|
||||
## Class: ChildProcess
|
||||
|
||||
`ChildProcess` is an `EventEmitter`.
|
||||
|
||||
Child processes always have three streams associated with them. `child.stdin`,
|
||||
`child.stdout`, and `child.stderr`. These may be shared with the stdio
|
||||
streams of the parent process, or they may be separate stream objects
|
||||
which can be piped to and from.
|
||||
|
||||
The ChildProcess class is not intended to be used directly. Use the
|
||||
`spawn()` or `fork()` methods to create a Child Process instance.
|
||||
|
||||
### Event: 'exit'
|
||||
|
||||
`function (code, signal) {}`
|
||||
* `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 after the child process ends. If the process terminated
|
||||
normally, `code` is the final exit code of the process, otherwise `null`. If
|
||||
@@ -33,19 +44,36 @@ An alternative way to check if you can send messages is to see if the
|
||||
|
||||
### child.stdin
|
||||
|
||||
* {Stream object}
|
||||
|
||||
A `Writable Stream` that represents the child process's `stdin`.
|
||||
Closing this stream via `end()` often causes the child process to terminate.
|
||||
|
||||
If the child stdio streams are shared with the parent, then this will
|
||||
not be set.
|
||||
|
||||
### child.stdout
|
||||
|
||||
* {Stream object}
|
||||
|
||||
A `Readable Stream` that represents the child process's `stdout`.
|
||||
|
||||
If the child stdio streams are shared with the parent, then this will
|
||||
not be set.
|
||||
|
||||
### child.stderr
|
||||
|
||||
* {Stream object}
|
||||
|
||||
A `Readable Stream` that represents the child process's `stderr`.
|
||||
|
||||
If the child stdio streams are shared with the parent, then this will
|
||||
not be set.
|
||||
|
||||
### child.pid
|
||||
|
||||
* {Integer}
|
||||
|
||||
The PID of the child process.
|
||||
|
||||
Example:
|
||||
@@ -56,8 +84,48 @@ Example:
|
||||
console.log('Spawned child pid: ' + grep.pid);
|
||||
grep.stdin.end();
|
||||
|
||||
### child.kill([signal])
|
||||
|
||||
### child_process.spawn(command, [args], [options])
|
||||
* `signal` {String}
|
||||
|
||||
Send a signal to the child process. If no argument is given, the process will
|
||||
be sent `'SIGTERM'`. See `signal(7)` for a list of available signals.
|
||||
|
||||
var spawn = require('child_process').spawn,
|
||||
grep = spawn('grep', ['ssh']);
|
||||
|
||||
grep.on('exit', function (code, signal) {
|
||||
console.log('child process terminated due to receipt of signal '+signal);
|
||||
});
|
||||
|
||||
// send SIGHUP to process
|
||||
grep.kill('SIGHUP');
|
||||
|
||||
Note that while the function is called `kill`, the signal delivered to the child
|
||||
process may not actually kill it. `kill` really just sends a signal to a process.
|
||||
|
||||
See `kill(2)`
|
||||
|
||||
### child.send(message, [sendHandle])
|
||||
|
||||
* `message` {Object}
|
||||
* `sendHandle` {Handle object}
|
||||
|
||||
Send a message (and, optionally, a handle object) to a child process.
|
||||
|
||||
See `child_process.fork()` for details.
|
||||
|
||||
## child_process.spawn(command, [args], [options])
|
||||
|
||||
* `command` {String} The command to run
|
||||
* `args` {Array} List of string arguments
|
||||
* `options` {Object}
|
||||
* `cwd` {String} Current working directory of the child process
|
||||
* `customFds` {Array} **Deprecated** File descriptors for the child to use
|
||||
for stdio. (See below)
|
||||
* `env` {Object} Environment key-value pairs
|
||||
* `setsid` {Boolean}
|
||||
* return: {ChildProcess object}
|
||||
|
||||
Launches a new process with the given `command`, with command line arguments in `args`.
|
||||
If omitted, `args` defaults to an empty Array.
|
||||
@@ -150,17 +218,34 @@ API.
|
||||
There is a deprecated option called `customFds` which allows one to specify
|
||||
specific file descriptors for the stdio of the child process. This API was
|
||||
not portable to all platforms and therefore removed.
|
||||
With `customFds` it was possible to hook up the new process' [stdin, stdout,
|
||||
stderr] to existing streams; `-1` meant that a new stream should be created.
|
||||
With `customFds` it was possible to hook up the new process' `[stdin, stdout,
|
||||
stderr]` to existing streams; `-1` meant that a new stream should be created.
|
||||
Use at your own risk.
|
||||
|
||||
There are several internal options. In particular `stdinStream`,
|
||||
`stdoutStream`, `stderrStream`. They are for INTERNAL USE ONLY. As with all
|
||||
undocumented APIs in Node, they should not be used.
|
||||
|
||||
See also: `child_process.exec()`
|
||||
See also: `child_process.exec()` and `child_process.fork()`
|
||||
|
||||
### child_process.exec(command, [options], callback)
|
||||
## 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
|
||||
* `customFds` {Array} **Deprecated** File descriptors for the child to use
|
||||
for stdio. (See below)
|
||||
* `env` {Object} Environment key-value pairs
|
||||
* `setsid` {Boolean}
|
||||
* `encoding` {String} (Default: 'utf8')
|
||||
* `timeout` {Number} (Default: 0)
|
||||
* `maxBuffer` {Number} (Default: 200*1024)
|
||||
* `killSignal` {String} (Default: 'SIGTERM')
|
||||
* `callback` {Function} called with the output when process terminates
|
||||
* `code` {Integer} Exit code
|
||||
* `stdout` {Buffer}
|
||||
* `stderr` {Buffer}
|
||||
* Return: ChildProcess object
|
||||
|
||||
Runs a command in a shell and buffers the output.
|
||||
|
||||
@@ -182,7 +267,8 @@ will be `null`. On error, `error` will be an instance of `Error` and `err.code`
|
||||
will be the exit code of the child process, and `err.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
|
||||
There is a second optional argument to specify several options. The
|
||||
default options are
|
||||
|
||||
{ encoding: 'utf8',
|
||||
timeout: 0,
|
||||
@@ -198,14 +284,48 @@ amount of data allowed on stdout or stderr - if this value is exceeded then
|
||||
the child process is killed.
|
||||
|
||||
|
||||
### child_process.execFile(file, args, options, callback)
|
||||
## 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
|
||||
* `customFds` {Array} **Deprecated** File descriptors for the child to use
|
||||
for stdio. (See below)
|
||||
* `env` {Object} Environment key-value pairs
|
||||
* `setsid` {Boolean}
|
||||
* `encoding` {String} (Default: 'utf8')
|
||||
* `timeout` {Number} (Default: 0)
|
||||
* `maxBuffer` {Number} (Default: 200*1024)
|
||||
* `killSignal` {String} (Default: 'SIGTERM')
|
||||
* `callback` {Function} called with the output when process terminates
|
||||
* `code` {Integer} Exit code
|
||||
* `stdout` {Buffer}
|
||||
* `stderr` {Buffer}
|
||||
* Return: ChildProcess object
|
||||
|
||||
This is similar to `child_process.exec()` except it does not execute a
|
||||
subshell but rather the specified file directly. This makes it slightly
|
||||
leaner than `child_process.exec`. It has the same options.
|
||||
|
||||
|
||||
### child_process.fork(modulePath, [arguments], [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
|
||||
* `customFds` {Array} **Deprecated** File descriptors for the child to use
|
||||
for stdio. (See below)
|
||||
* `env` {Object} Environment key-value pairs
|
||||
* `setsid` {Boolean}
|
||||
* `encoding` {String} (Default: 'utf8')
|
||||
* `timeout` {Number} (Default: 0)
|
||||
* `callback` {Function} called with the output when process terminates
|
||||
* `code` {Integer} Exit code
|
||||
* `stdout` {Buffer}
|
||||
* `stderr` {Buffer}
|
||||
* Return: ChildProcess object
|
||||
|
||||
This is a special case of the `spawn()` functionality for spawning Node
|
||||
processes. In addition to having all the methods in a normal ChildProcess
|
||||
@@ -278,22 +398,3 @@ there is no IPC channel keeping it alive. When calling this method the
|
||||
`connected` flag will be set to `false`. Please note that you can also call
|
||||
`process.disconnect()` in the child process.
|
||||
|
||||
### child.kill([signal])
|
||||
|
||||
Send a signal to the child process. If no argument is given, the process will
|
||||
be sent `'SIGTERM'`. See `signal(7)` for a list of available signals.
|
||||
|
||||
var spawn = require('child_process').spawn,
|
||||
grep = spawn('grep', ['ssh']);
|
||||
|
||||
grep.on('exit', function (code, signal) {
|
||||
console.log('child process terminated due to receipt of signal '+signal);
|
||||
});
|
||||
|
||||
// send SIGHUP to process
|
||||
grep.kill('SIGHUP');
|
||||
|
||||
Note that while the function is called `kill`, the signal delivered to the child
|
||||
process may not actually kill it. `kill` really just sends a signal to a process.
|
||||
|
||||
See `kill(2)`
|
||||
+123
-57
@@ -1,4 +1,6 @@
|
||||
## Cluster
|
||||
# Cluster
|
||||
|
||||
Stability: 1 - Experimental
|
||||
|
||||
A single instance of Node runs in a single thread. To take advantage of
|
||||
multi-core systems the user will sometimes want to launch a cluster of Node
|
||||
@@ -36,19 +38,40 @@ Running node will now share port 8000 between the workers:
|
||||
Worker 2437 online
|
||||
|
||||
|
||||
### cluster.isMaster
|
||||
This feature was introduced recently, and may change in future versions.
|
||||
Please try it out and provide feedback.
|
||||
|
||||
This boolean flag is true if the process is a master. This is determined
|
||||
## cluster.settings
|
||||
|
||||
* {Object}
|
||||
* `exec` {String} file path to worker file. (Default=`__filename`)
|
||||
* `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`)
|
||||
|
||||
All settings set by the `.setupMaster` is stored in this settings object.
|
||||
This object is not supposed to be change 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 `isMaster` is `true`.
|
||||
undefined, then `isMaster` is `true`.
|
||||
|
||||
### cluster.isWorker
|
||||
## cluster.isWorker
|
||||
|
||||
* {Boolean}
|
||||
|
||||
This boolean flag is true if the process is a worker forked from a master.
|
||||
If the `process.env.NODE_UNIQUE_ID` is set to a value different efined
|
||||
If the `process.env.NODE_UNIQUE_ID` is set to a value, then
|
||||
`isWorker` is `true`.
|
||||
|
||||
### Event: 'fork'
|
||||
## 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 you own timeout.
|
||||
@@ -69,19 +92,23 @@ This can be used to log worker activity, and create you own timeout.
|
||||
errorMsg();
|
||||
});
|
||||
|
||||
### Event: 'online'
|
||||
## Event: 'online'
|
||||
|
||||
* `worker` {Worker object}
|
||||
|
||||
After forking a new worker, the worker should respond with a online message.
|
||||
When the master receives a online message it will emit such event.
|
||||
The difference between 'fork' and 'online' is that fork is emitted when the
|
||||
master tries to fork a worker, and 'online' is emitted when the worker is being
|
||||
executed.
|
||||
master tries to fork a worker, and 'online' is emitted when the worker is
|
||||
being executed.
|
||||
|
||||
cluster.on('online', function (worker) {
|
||||
console.log("Yay, the worker responded after it was forked");
|
||||
});
|
||||
|
||||
### Event: 'listening'
|
||||
## Event: 'listening'
|
||||
|
||||
* `worker` {Worker object}
|
||||
|
||||
When calling `listen()` from a worker, a 'listening' event is automatically assigned
|
||||
to the server instance. When the server is listening a message is send to the master
|
||||
@@ -91,7 +118,9 @@ where the 'listening' event is emitted.
|
||||
console.log("We are now connected");
|
||||
});
|
||||
|
||||
### Event: 'death'
|
||||
## Event: 'death'
|
||||
|
||||
* `worker` {Worker object}
|
||||
|
||||
When any of the workers die the cluster module will emit the 'death' event.
|
||||
This can be used to restart the worker by calling `fork()` again.
|
||||
@@ -101,15 +130,25 @@ This can be used to restart the worker by calling `fork()` again.
|
||||
cluster.fork();
|
||||
});
|
||||
|
||||
### Event 'setup'
|
||||
## Event: 'setup'
|
||||
|
||||
When the `.setupMaster()` function has been executed this event emits. If `.setupMaster()`
|
||||
was not executed before `fork()` this function will call `.setupMaster()` with no arguments.
|
||||
* `worker` {Worker object}
|
||||
|
||||
### cluster.setupMaster([options])
|
||||
When the `.setupMaster()` function has been executed this event emits.
|
||||
If `.setupMaster()` was not executed before `fork()` this function will
|
||||
call `.setupMaster()` with no arguments.
|
||||
|
||||
The `setupMaster` is used to change the default 'fork' behavior. It takes one option
|
||||
object argument.
|
||||
## cluster.setupMaster([settings])
|
||||
|
||||
* `settings` {Object}
|
||||
* `exec` {String} file path to worker file. (Default=`__filename`)
|
||||
* `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`)
|
||||
|
||||
The `setupMaster` is used to change the default 'fork' behavior. It takes
|
||||
one option object argument.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -121,26 +160,28 @@ Example:
|
||||
});
|
||||
cluster.autoFork();
|
||||
|
||||
The options argument can contain 3 different properties.
|
||||
## cluster.fork([env])
|
||||
|
||||
- `exec` are the file path to the worker file, by default this is the same file as the master.
|
||||
- `args` are a array of arguments send along with the worker, by default this is `process.argv.slice(2)`.
|
||||
- `silent`, if this option is true the output of a worker won't propagate to the master, by default this is false.
|
||||
|
||||
### cluster.settings
|
||||
|
||||
All settings set by the `.setupMaster` is stored in this settings object.
|
||||
This object is not supposed to be change or set manually, by you.
|
||||
|
||||
All propertys are `undefined` if they are not yet set.
|
||||
|
||||
### cluster.fork([env])
|
||||
* `env` {Object} Key/value pairs to add to child process environment.
|
||||
* return {Worker object}
|
||||
|
||||
Spawn a new worker process. This can only be called from the master process.
|
||||
The function takes an optional `env` object. The properties in this object
|
||||
will be added to the process environment in the worker.
|
||||
|
||||
### cluster.workers
|
||||
## cluster.settings
|
||||
|
||||
* {Object}
|
||||
* `exec` {String} file path to worker file. Default: `__filename`
|
||||
* `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`)
|
||||
|
||||
All settings set by the `.setupMaster` is stored in this settings object.
|
||||
This object is not supposed to be change or set manually.
|
||||
|
||||
## cluster.workers
|
||||
|
||||
* {Object}
|
||||
|
||||
In the cluster all living worker objects are stored in this object by there
|
||||
`uniqueID` as the key. This makes it easy to loop through all living workers.
|
||||
@@ -162,27 +203,48 @@ the worker's uniqueID is the easiest way to find the worker.
|
||||
var worker = cluster.workers[uniqueID];
|
||||
});
|
||||
|
||||
## Worker
|
||||
## Class: Worker
|
||||
|
||||
This object contains all public information and method about a worker.
|
||||
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.uniqueID
|
||||
### worker.uniqueID
|
||||
|
||||
Each new worker is given its own unique id, this id is stored in the `uniqueID`.
|
||||
* {String}
|
||||
|
||||
### Worker.process
|
||||
Each new worker is given its own unique id, this id is stored in the
|
||||
`uniqueID`.
|
||||
|
||||
All workers are created using `child_process.fork()`, the returned object from this
|
||||
function is stored in process.
|
||||
While a worker is alive, this is the key that indexes it in
|
||||
cluster.workers
|
||||
|
||||
### Worker.send(message, [sendHandle])
|
||||
### worker.process
|
||||
|
||||
This function is equal to the send methods provided by `child_process.fork()`.
|
||||
In the master you should use this function to send a message to a specific worker.
|
||||
However in a worker you can also use `process.send(message)`, since this is the same
|
||||
function.
|
||||
* {ChildProcess object}
|
||||
|
||||
All workers are created using `child_process.fork()`, the returned object
|
||||
from this function is stored in process.
|
||||
|
||||
See: [Child Process module](child_process.html)
|
||||
|
||||
### worker.suicide
|
||||
|
||||
* {Boolean}
|
||||
|
||||
This property is a boolean. It is set when a worker dies, until then it is
|
||||
`undefined`. It is true if the worker was killed using the `.destroy()`
|
||||
method, and false otherwise.
|
||||
|
||||
### worker.send(message, [sendHandle])
|
||||
|
||||
* `message` {Object}
|
||||
* `sendHandle` {Handle object}
|
||||
|
||||
This function is equal to the send methods provided by
|
||||
`child_process.fork()`. In the master you should use this function to
|
||||
send a message to a specific worker. However in a worker you can also use
|
||||
`process.send(message)`, since this is the same function.
|
||||
|
||||
This example will echo back all messages from the master:
|
||||
|
||||
@@ -196,10 +258,11 @@ This example will echo back all messages from the master:
|
||||
});
|
||||
}
|
||||
|
||||
### Worker.destroy()
|
||||
### worker.destroy()
|
||||
|
||||
This function will kill the worker, and inform the master to not spawn a new worker.
|
||||
To know the difference between suicide and accidentally death a suicide boolean is set to true.
|
||||
This function will kill the worker, and inform the master to not spawn a
|
||||
new worker. To know the difference between suicide and accidentally death
|
||||
a suicide boolean is set to true.
|
||||
|
||||
cluster.on('death', function (worker) {
|
||||
if (worker.suicide === true) {
|
||||
@@ -210,12 +273,9 @@ To know the difference between suicide and accidentally death a suicide boolean
|
||||
// destroy worker
|
||||
worker.destroy();
|
||||
|
||||
### Worker.suicide
|
||||
### Event: 'message'
|
||||
|
||||
This property is a boolean. It is set when a worker dies, until then it is `undefined`.
|
||||
It is true if the worker was killed using the `.destroy()` method, and false otherwise.
|
||||
|
||||
### Event: message
|
||||
* `message` {Object}
|
||||
|
||||
This event is the same as the one provided by `child_process.fork()`.
|
||||
In the master you should use this event, however in a worker you can also use
|
||||
@@ -260,7 +320,9 @@ in the master process using the message system:
|
||||
}).listen(8000);
|
||||
}
|
||||
|
||||
### Event: online
|
||||
### Event: 'online'
|
||||
|
||||
* `worker` {Worker object}
|
||||
|
||||
Same as the `cluster.on('online')` event, but emits only when the state change
|
||||
on the specified worker.
|
||||
@@ -269,7 +331,9 @@ on the specified worker.
|
||||
// Worker is online
|
||||
};
|
||||
|
||||
### Event: listening
|
||||
### Event: 'listening'
|
||||
|
||||
* `worker` {Worker object}
|
||||
|
||||
Same as the `cluster.on('listening')` event, but emits only when the state change
|
||||
on the specified worker.
|
||||
@@ -278,7 +342,9 @@ on the specified worker.
|
||||
// Worker is listening
|
||||
};
|
||||
|
||||
### Event: death
|
||||
### Event: 'death'
|
||||
|
||||
* `worker` {Worker object}
|
||||
|
||||
Same as the `cluster.on('death')` event, but emits only when the state change
|
||||
on the specified worker.
|
||||
|
||||
+59
-18
@@ -1,4 +1,4 @@
|
||||
## Crypto
|
||||
# Crypto
|
||||
|
||||
Use `require('crypto')` to access this module.
|
||||
|
||||
@@ -8,7 +8,7 @@ of a secure HTTPS net or http connection.
|
||||
|
||||
It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.
|
||||
|
||||
### crypto.createCredentials(details)
|
||||
## crypto.createCredentials(details)
|
||||
|
||||
Creates a credentials object, with the optional details being a dictionary with keys:
|
||||
|
||||
@@ -23,7 +23,7 @@ If no 'ca' details are given, then node.js will use the default publicly trusted
|
||||
<http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt>.
|
||||
|
||||
|
||||
### crypto.createHash(algorithm)
|
||||
## crypto.createHash(algorithm)
|
||||
|
||||
Creates and returns a hash object, a cryptographic hash with the given algorithm
|
||||
which can be used to generate hash digests.
|
||||
@@ -50,6 +50,12 @@ Example: this program that takes the sha1 sum of a file
|
||||
console.log(d + ' ' + filename);
|
||||
});
|
||||
|
||||
## Class: Hash
|
||||
|
||||
The class for creating hash digests of data.
|
||||
|
||||
Returned by `crypto.createHash`.
|
||||
|
||||
### hash.update(data, [input_encoding])
|
||||
|
||||
Updates the hash content with the given `data`, the encoding of which is given
|
||||
@@ -66,13 +72,19 @@ Defaults to `'binary'`.
|
||||
Note: `hash` object can not be used after `digest()` method been called.
|
||||
|
||||
|
||||
### crypto.createHmac(algorithm, key)
|
||||
## crypto.createHmac(algorithm, key)
|
||||
|
||||
Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.
|
||||
|
||||
`algorithm` is dependent on the available algorithms supported by OpenSSL - see createHash above.
|
||||
`key` is the hmac key to be used.
|
||||
|
||||
## Class: Hmac
|
||||
|
||||
Class for creating cryptographic hmac content.
|
||||
|
||||
Returned by `crypto.createHmac`.
|
||||
|
||||
### hmac.update(data)
|
||||
|
||||
Update the hmac content with the given `data`.
|
||||
@@ -87,7 +99,7 @@ Defaults to `'binary'`.
|
||||
Note: `hmac` object can not be used after `digest()` method been called.
|
||||
|
||||
|
||||
### crypto.createCipher(algorithm, password)
|
||||
## crypto.createCipher(algorithm, password)
|
||||
|
||||
Creates and returns a cipher object, with the given algorithm and password.
|
||||
|
||||
@@ -95,15 +107,21 @@ Creates and returns a cipher object, with the given algorithm and password.
|
||||
On recent releases, `openssl list-cipher-algorithms` will display the
|
||||
available cipher algorithms.
|
||||
`password` is used to derive key and IV, which must be `'binary'` encoded
|
||||
string (See the [Buffers](buffers.html) for more information).
|
||||
string (See the [Buffer section](buffer.html) for more information).
|
||||
|
||||
### crypto.createCipheriv(algorithm, key, iv)
|
||||
## crypto.createCipheriv(algorithm, key, iv)
|
||||
|
||||
Creates and returns a cipher object, with the given algorithm, key and iv.
|
||||
|
||||
`algorithm` is the same as the `createCipher()`. `key` is a raw key used in
|
||||
algorithm. `iv` is an Initialization vector. `key` and `iv` must be `'binary'`
|
||||
encoded string (See the [Buffers](buffers.html) for more information).
|
||||
encoded string (See the [Buffer section](buffer.html) for more information).
|
||||
|
||||
## Class: Cipher
|
||||
|
||||
Class for encrypting data.
|
||||
|
||||
Returned by `crypto.createCipher` and `crypto.createCipheriv`.
|
||||
|
||||
### cipher.update(data, [input_encoding], [output_encoding])
|
||||
|
||||
@@ -130,16 +148,22 @@ the length of the entire input data must be a multiple of the cipher's block siz
|
||||
Useful for non-standard padding, e.g. using `0x0` instead of PKCS padding. You must call this before `cipher.final`.
|
||||
|
||||
|
||||
### crypto.createDecipher(algorithm, password)
|
||||
## crypto.createDecipher(algorithm, password)
|
||||
|
||||
Creates and returns a decipher object, with the given algorithm and key.
|
||||
This is the mirror of the [createCipher()](#crypto.createCipher) above.
|
||||
|
||||
### crypto.createDecipheriv(algorithm, key, iv)
|
||||
## crypto.createDecipheriv(algorithm, key, iv)
|
||||
|
||||
Creates and returns a decipher object, with the given algorithm, key and iv.
|
||||
This is the mirror of the [createCipheriv()](#crypto.createCipheriv) above.
|
||||
|
||||
## Class: Decipher
|
||||
|
||||
Class for decrypting data.
|
||||
|
||||
Returned by `crypto.createDecipher` and `crypto.createDecipheriv`.
|
||||
|
||||
### decipher.update(data, [input_encoding], [output_encoding])
|
||||
|
||||
Updates the decipher with `data`, which is encoded in `'binary'`, `'base64'`
|
||||
@@ -163,12 +187,18 @@ You can disable auto padding if the data has been encrypted without standard blo
|
||||
ciphers block size. You must call this before streaming data to `decipher.update`.
|
||||
|
||||
|
||||
### crypto.createSign(algorithm)
|
||||
## crypto.createSign(algorithm)
|
||||
|
||||
Creates and returns a signing object, with the given algorithm.
|
||||
On recent OpenSSL releases, `openssl list-public-key-algorithms` will display
|
||||
the available signing algorithms. Examples are `'RSA-SHA256'`.
|
||||
|
||||
## Class: Signer
|
||||
|
||||
Class for generating signatures.
|
||||
|
||||
Returned by `crypto.createSign`.
|
||||
|
||||
### signer.update(data)
|
||||
|
||||
Updates the signer object with data.
|
||||
@@ -184,12 +214,17 @@ Returns the signature in `output_format` which can be `'binary'`, `'hex'` or
|
||||
|
||||
Note: `signer` object can not be used after `sign()` method been called.
|
||||
|
||||
|
||||
### crypto.createVerify(algorithm)
|
||||
## crypto.createVerify(algorithm)
|
||||
|
||||
Creates and returns a verification object, with the given algorithm.
|
||||
This is the mirror of the signing object above.
|
||||
|
||||
## Class: Verify
|
||||
|
||||
Class for verifying signatures.
|
||||
|
||||
Returned by `crypto.createVerify`.
|
||||
|
||||
### verifier.update(data)
|
||||
|
||||
Updates the verifier object with data.
|
||||
@@ -207,17 +242,23 @@ Returns true or false depending on the validity of the signature for the data an
|
||||
|
||||
Note: `verifier` object can not be used after `verify()` method been called.
|
||||
|
||||
### crypto.createDiffieHellman(prime_length)
|
||||
## crypto.createDiffieHellman(prime_length)
|
||||
|
||||
Creates a Diffie-Hellman key exchange object and generates a prime of the
|
||||
given bit length. The generator used is `2`.
|
||||
|
||||
### crypto.createDiffieHellman(prime, [encoding])
|
||||
## crypto.createDiffieHellman(prime, [encoding])
|
||||
|
||||
Creates a Diffie-Hellman key exchange object using the supplied prime. The
|
||||
generator used is `2`. Encoding can be `'binary'`, `'hex'`, or `'base64'`.
|
||||
Defaults to `'binary'`.
|
||||
|
||||
## Class: DiffieHellman
|
||||
|
||||
The class for creating Diffie-Hellman key exchanges.
|
||||
|
||||
Returned by `crypto.createDiffieHellman`.
|
||||
|
||||
### diffieHellman.generateKeys([encoding])
|
||||
|
||||
Generates private and public Diffie-Hellman key values, and returns the
|
||||
@@ -264,7 +305,7 @@ or `'base64'`. Defaults to `'binary'`.
|
||||
Sets the Diffie-Hellman private key. Key encoding can be `'binary'`, `'hex'`,
|
||||
or `'base64'`. Defaults to `'binary'`.
|
||||
|
||||
### crypto.getDiffieHellman(group_name)
|
||||
## crypto.getDiffieHellman(group_name)
|
||||
|
||||
Creates a predefined Diffie-Hellman key exchange object.
|
||||
The supported groups are: `'modp1'`, `'modp2'`, `'modp5'`
|
||||
@@ -294,13 +335,13 @@ Example (obtaining a shared secret):
|
||||
/* alice_secret and bob_secret should be the same */
|
||||
console.log(alice_secret == bob_secret);
|
||||
|
||||
### pbkdf2(password, salt, iterations, keylen, callback)
|
||||
## crypto.pbkdf2(password, salt, iterations, keylen, callback)
|
||||
|
||||
Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive
|
||||
a key of given length from the given password, salt and iterations.
|
||||
The callback gets two arguments `(err, derivedKey)`.
|
||||
|
||||
### randomBytes(size, [callback])
|
||||
## crypto.randomBytes(size, [callback])
|
||||
|
||||
Generates cryptographically strong pseudo-random data. Usage:
|
||||
|
||||
|
||||
+11
-11
@@ -1,4 +1,6 @@
|
||||
## Debugger
|
||||
# Debugger
|
||||
|
||||
<!-- type=misc -->
|
||||
|
||||
V8 comes with an extensive debugger which is accessible out-of-process via a
|
||||
simple [TCP protocol](http://code.google.com/p/v8/wiki/DebuggerProtocol).
|
||||
@@ -74,7 +76,7 @@ The `repl` command allows you to evaluate code remotely. The `next` command
|
||||
steps over to the next line. There are a few other commands available and more
|
||||
to come. Type `help` to see others.
|
||||
|
||||
### Watchers
|
||||
## Watchers
|
||||
|
||||
You can watch expression and variable values while debugging your code.
|
||||
On every breakpoint each expression from the watchers list will be evaluated
|
||||
@@ -85,9 +87,9 @@ To start watching an expression, type `watch("my_expression")`. `watchers`
|
||||
prints the active watchers. To remove a watcher, type
|
||||
`unwatch("my_expression")`.
|
||||
|
||||
### Commands reference
|
||||
## Commands reference
|
||||
|
||||
#### Stepping
|
||||
### Stepping
|
||||
|
||||
* `cont`, `c` - Continue execution
|
||||
* `next`, `n` - Step next
|
||||
@@ -95,7 +97,7 @@ prints the active watchers. To remove a watcher, type
|
||||
* `out`, `o` - Step out
|
||||
* `pause` - Pause running code (like pause button in Developer TOols)
|
||||
|
||||
#### Breakpoints
|
||||
### Breakpoints
|
||||
|
||||
* `setBreakpoint()`, `sb()` - Set breakpoint on current line
|
||||
* `setBreakpoint(line)`, `sb(line)` - Set breakpoint on specific line
|
||||
@@ -105,7 +107,7 @@ functions body
|
||||
script.js
|
||||
* `clearBreakpoint`, `cb(...)` - Clear breakpoint
|
||||
|
||||
#### Info
|
||||
### Info
|
||||
|
||||
* `backtrace`, `bt` - Print backtrace of current execution frame
|
||||
* `list(5)` - List scripts source code with 5 line context (5 lines before and
|
||||
@@ -116,21 +118,19 @@ after)
|
||||
breakpoint)
|
||||
* `repl` - Open debugger's repl for evaluation in debugging script's context
|
||||
|
||||
#### Execution control
|
||||
### Execution control
|
||||
|
||||
* `run` - Run script (automatically runs on debugger's start)
|
||||
* `restart` - Restart script
|
||||
* `kill` - Kill script
|
||||
|
||||
#### Various
|
||||
### Various
|
||||
|
||||
* `scripts` - List all loaded scripts
|
||||
* `version` - Display v8's version
|
||||
|
||||
### Advanced Usage
|
||||
## Advanced Usage
|
||||
|
||||
The V8 debugger can be enabled and accessed either by starting Node with
|
||||
the `--debug` command-line flag or by signaling an existing Node process
|
||||
with `SIGUSR1`.
|
||||
|
||||
|
||||
+63
-31
@@ -1,39 +1,17 @@
|
||||
## UDP / Datagram Sockets
|
||||
# UDP / Datagram Sockets
|
||||
|
||||
<!-- name=dgram -->
|
||||
|
||||
Datagram sockets are available through `require('dgram')`.
|
||||
|
||||
### Event: 'message'
|
||||
## dgram.createSocket(type, [callback])
|
||||
|
||||
`function (msg, rinfo) { }`
|
||||
* `type` String. Either 'udp4' or 'udp6'
|
||||
* `callback` Function. Attached as a listener to `message` events.
|
||||
Optional
|
||||
* Returns: Socket object
|
||||
|
||||
Emitted when a new datagram is available on a socket. `msg` is a `Buffer` and `rinfo` is
|
||||
an object with the sender's address information and the number of bytes in the datagram.
|
||||
|
||||
### Event: 'listening'
|
||||
|
||||
`function () { }`
|
||||
|
||||
Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets
|
||||
are created.
|
||||
|
||||
### Event: 'close'
|
||||
|
||||
`function () { }`
|
||||
|
||||
Emitted when a socket is closed with `close()`. No new `message` events will be emitted
|
||||
on this socket.
|
||||
|
||||
### Event: 'error'
|
||||
|
||||
`function (exception) {}`
|
||||
|
||||
Emitted when an error occurs.
|
||||
|
||||
---
|
||||
|
||||
### dgram.createSocket(type, [callback])
|
||||
|
||||
Creates a datagram socket of the specified types. Valid types are `udp4`
|
||||
Creates a datagram Socket of the specified types. Valid types are `udp4`
|
||||
and `udp6`.
|
||||
|
||||
Takes an optional callback which is added as a listener for `message` events.
|
||||
@@ -43,8 +21,45 @@ to the "all interfaces" address on a random port (it does the right thing for
|
||||
both `udp4` and `udp6` sockets). You can then retrieve the address and port
|
||||
with `socket.address().address` and `socket.address().port`.
|
||||
|
||||
## Class: Socket
|
||||
|
||||
The dgram Socket class encapsulates the datagram functionality. It
|
||||
should be created via `dgram.createSocket(type, [callback])`.
|
||||
|
||||
### Event: 'message'
|
||||
|
||||
* `msg` Buffer object. The message
|
||||
* `rinfo` Object. Remote address information
|
||||
|
||||
Emitted when a new datagram is available on a socket. `msg` is a `Buffer` and `rinfo` is
|
||||
an object with the sender's address information and the number of bytes in the datagram.
|
||||
|
||||
### Event: 'listening'
|
||||
|
||||
Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets
|
||||
are created.
|
||||
|
||||
### Event: 'close'
|
||||
|
||||
Emitted when a socket is closed with `close()`. No new `message` events will be emitted
|
||||
on this socket.
|
||||
|
||||
### Event: 'error'
|
||||
|
||||
* `exception` Error object
|
||||
|
||||
Emitted when an error occurs.
|
||||
|
||||
### dgram.send(buf, offset, length, port, address, [callback])
|
||||
|
||||
* `buf` Buffer object. Message to be sent
|
||||
* `offset` Integer. Offset in the buffer where the message starts.
|
||||
* `length` Integer. Number of bytes in the message.
|
||||
* `port` Integer. destination port
|
||||
* `address` String. destination IP
|
||||
* `callback` Function. Callback when message is done being delivered.
|
||||
Optional.
|
||||
|
||||
For UDP sockets, the destination port and IP address must be specified. A string
|
||||
may be supplied for the `address` parameter, and it will be resolved with DNS. An
|
||||
optional callback may be specified to detect any DNS errors and when `buf` may be
|
||||
@@ -93,6 +108,9 @@ informing the source that the data did not reach its intended recipient).
|
||||
|
||||
### dgram.bind(port, [address])
|
||||
|
||||
* `port` Integer
|
||||
* `address` String, Optional
|
||||
|
||||
For UDP sockets, listen for datagrams on a named `port` and optional `address`. If
|
||||
`address` is not specified, the OS will try to listen on all addresses.
|
||||
|
||||
@@ -128,11 +146,15 @@ this object will contain `address` and `port`.
|
||||
|
||||
### dgram.setBroadcast(flag)
|
||||
|
||||
* `flag` Boolean
|
||||
|
||||
Sets or clears the `SO_BROADCAST` socket option. When this option is set, UDP packets
|
||||
may be sent to a local interface's broadcast address.
|
||||
|
||||
### dgram.setTTL(ttl)
|
||||
|
||||
* `ttl` Integer
|
||||
|
||||
Sets the `IP_TTL` socket option. TTL stands for "Time to Live," but in this context it
|
||||
specifies the number of IP hops that a packet is allowed to go through. Each router or
|
||||
gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a
|
||||
@@ -144,6 +166,8 @@ systems is 64.
|
||||
|
||||
### dgram.setMulticastTTL(ttl)
|
||||
|
||||
* `ttl` Integer
|
||||
|
||||
Sets the `IP_MULTICAST_TTL` socket option. TTL stands for "Time to Live," but in this
|
||||
context it specifies the number of IP hops that a packet is allowed to go through,
|
||||
specifically for multicast traffic. Each router or gateway that forwards a packet
|
||||
@@ -154,11 +178,16 @@ systems is 64.
|
||||
|
||||
### dgram.setMulticastLoopback(flag)
|
||||
|
||||
* `flag` Boolean
|
||||
|
||||
Sets or clears the `IP_MULTICAST_LOOP` socket option. When this option is set, multicast
|
||||
packets will also be received on the local interface.
|
||||
|
||||
### dgram.addMembership(multicastAddress, [multicastInterface])
|
||||
|
||||
* `multicastAddress` String
|
||||
* `multicastInterface` String, Optional
|
||||
|
||||
Tells the kernel to join a multicast group with `IP_ADD_MEMBERSHIP` socket option.
|
||||
|
||||
If `multicastInterface` is not specified, the OS will try to add membership to all valid
|
||||
@@ -166,6 +195,9 @@ interfaces.
|
||||
|
||||
### dgram.dropMembership(multicastAddress, [multicastInterface])
|
||||
|
||||
* `multicastAddress` String
|
||||
* `multicastInterface` String, Optional
|
||||
|
||||
Opposite of `addMembership` - tells the kernel to leave a multicast group with
|
||||
`IP_DROP_MEMBERSHIP` socket option. This is automatically called by the kernel
|
||||
when the socket is closed or process terminates, so most apps will never need to call
|
||||
|
||||
+11
-11
@@ -1,4 +1,4 @@
|
||||
## DNS
|
||||
# DNS
|
||||
|
||||
Use `require('dns')` to access this module. All methods in the dns module
|
||||
use C-Ares except for `dns.lookup` which uses `getaddrinfo(3)` in a thread
|
||||
@@ -31,7 +31,7 @@ resolves the IP addresses which are returned.
|
||||
});
|
||||
});
|
||||
|
||||
### dns.lookup(domain, [family], callback)
|
||||
## dns.lookup(domain, [family], callback)
|
||||
|
||||
Resolves a domain (e.g. `'google.com'`) into the first found A (IPv4) or
|
||||
AAAA (IPv6) record.
|
||||
@@ -44,7 +44,7 @@ is either the integer 4 or 6 and denotes the family of `address` (not
|
||||
necessarily the value initially passed to `lookup`).
|
||||
|
||||
|
||||
### dns.resolve(domain, [rrtype], callback)
|
||||
## dns.resolve(domain, [rrtype], callback)
|
||||
|
||||
Resolves a domain (e.g. `'google.com'`) into an array of the record types
|
||||
specified by rrtype. Valid rrtypes are `'A'` (IPV4 addresses, default),
|
||||
@@ -61,50 +61,50 @@ one of the error codes listed below and `err.message` is a string describing
|
||||
the error in English.
|
||||
|
||||
|
||||
### dns.resolve4(domain, callback)
|
||||
## dns.resolve4(domain, callback)
|
||||
|
||||
The same as `dns.resolve()`, but only for IPv4 queries (`A` records).
|
||||
`addresses` is an array of IPv4 addresses (e.g.
|
||||
`['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
|
||||
|
||||
### dns.resolve6(domain, callback)
|
||||
## dns.resolve6(domain, callback)
|
||||
|
||||
The same as `dns.resolve4()` except for IPv6 queries (an `AAAA` query).
|
||||
|
||||
|
||||
### dns.resolveMx(domain, callback)
|
||||
## dns.resolveMx(domain, callback)
|
||||
|
||||
The same as `dns.resolve()`, but only for mail exchange queries (`MX` records).
|
||||
|
||||
`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(domain, callback)
|
||||
## dns.resolveTxt(domain, callback)
|
||||
|
||||
The same as `dns.resolve()`, but only for text queries (`TXT` records).
|
||||
`addresses` is an array of the text records available for `domain` (e.g.,
|
||||
`['v=spf1 ip4:0.0.0.0 ~all']`).
|
||||
|
||||
### dns.resolveSrv(domain, callback)
|
||||
## dns.resolveSrv(domain, callback)
|
||||
|
||||
The same as `dns.resolve()`, but only for service records (`SRV` records).
|
||||
`addresses` is an array of the SRV records available for `domain`. Properties
|
||||
of SRV records are priority, weight, port, and name (e.g.,
|
||||
`[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]`).
|
||||
|
||||
### dns.reverse(ip, callback)
|
||||
## dns.reverse(ip, callback)
|
||||
|
||||
Reverse resolves an ip address to an array of domain names.
|
||||
|
||||
The callback has arguments `(err, domains)`.
|
||||
|
||||
### dns.resolveNs(domain, callback)
|
||||
## dns.resolveNs(domain, callback)
|
||||
|
||||
The same as `dns.resolve()`, but only for name server records (`NS` records).
|
||||
`addresses` is an array of the name server records available for `domain`
|
||||
(e.g., `['ns1.example.com', 'ns2.example.com']`).
|
||||
|
||||
### dns.resolveCname(domain, callback)
|
||||
## dns.resolveCname(domain, callback)
|
||||
|
||||
The same as `dns.resolve()`, but only for canonical name records (`CNAME`
|
||||
records). `addresses` is an array of the canonical name records available for
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# About this Documentation
|
||||
|
||||
<!-- type=misc -->
|
||||
|
||||
The goal of this documentation is to comprehensively explain the Node.js
|
||||
API, both from a reference as well as a conceptual point of view. Each
|
||||
section describes a built-in module or high-level concept.
|
||||
|
||||
Where appropriate, property types, method arguments, and the arguments
|
||||
provided to event handlers are detailed in a list underneath the topic
|
||||
heading.
|
||||
|
||||
Every `.html` document has a corresponding `.json` document presenting
|
||||
the same information in a structured manner. This feature is
|
||||
experimental, and added for the benefit of IDEs and other utilities that
|
||||
wish to do programmatic things with the documentation.
|
||||
|
||||
Every `.html` and `.json` file is generated based on the corresponding
|
||||
`.markdown` file in the `doc/api/` folder in node's source tree. The
|
||||
documentation is generated using the `tools/doc/generate.js` program.
|
||||
The HTML template is located at `doc/template.html`.
|
||||
|
||||
## Stability Index
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
Throughout the documentation, you will see indications of a section's
|
||||
stability. The Node.js API is still somewhat changing, and as it
|
||||
matures, certain parts are more reliable than others. Some are so
|
||||
proven, and so relied upon, that they are unlikely to ever change at
|
||||
all. Others are brand new and experimental, or known to be hazardous
|
||||
and in the process of being redesigned.
|
||||
|
||||
The notices look like this:
|
||||
|
||||
Stability: 1 Experimental
|
||||
|
||||
The stability indices are as follows:
|
||||
|
||||
* **0 - Deprecated** This feature is known to be problematic, and changes are
|
||||
planned. Do not rely on it. Use of the feature may cause warnings. Backwards
|
||||
compatibility should not be expected.
|
||||
|
||||
* **1 - Experimental** This feature was introduced recently, and may change
|
||||
or be removed in future versions. Please try it out and provide feedback.
|
||||
If it addresses a use-case that is important to you, tell the node core team.
|
||||
|
||||
* **2 - Unstable** The API is in the process of settling, but has not yet had
|
||||
sufficient real-world testing to be considered stable. Backwards-compatibility
|
||||
will be maintained if reasonable.
|
||||
|
||||
* **3 - Stable** The API has proven satisfactory, but cleanup in the underlying
|
||||
code may cause minor changes. Backwards-compatibility is guaranteed.
|
||||
|
||||
* **4 - API Frozen** This API has been tested extensively in production and is
|
||||
unlikely to ever have to change.
|
||||
|
||||
* **5 - Locked** Unless serious bugs are found, this code will not ever
|
||||
change. Please do not suggest changes in this area; they will be refused.
|
||||
+15
-12
@@ -1,4 +1,6 @@
|
||||
## Events
|
||||
# Events
|
||||
|
||||
<!--type=module-->
|
||||
|
||||
Many objects in Node emit events: a `net.Server` emits an event each time
|
||||
a peer connects to it, a `fs.readStream` emits an event when the file is
|
||||
@@ -12,7 +14,7 @@ Functions can then be attached to objects, to be executed when an event
|
||||
is emitted. These functions are called _listeners_.
|
||||
|
||||
|
||||
### events.EventEmitter
|
||||
## Class: events.EventEmitter
|
||||
|
||||
To access the EventEmitter class, `require('events').EventEmitter`.
|
||||
|
||||
@@ -24,8 +26,8 @@ trace and exit the program.
|
||||
All EventEmitters emit the event `'newListener'` when new listeners are
|
||||
added.
|
||||
|
||||
#### emitter.addListener(event, listener)
|
||||
#### emitter.on(event, listener)
|
||||
### emitter.addListener(event, listener)
|
||||
### emitter.on(event, listener)
|
||||
|
||||
Adds a listener to the end of the listeners array for the specified event.
|
||||
|
||||
@@ -33,7 +35,7 @@ Adds a listener to the end of the listeners array for the specified event.
|
||||
console.log('someone connected!');
|
||||
});
|
||||
|
||||
#### emitter.once(event, listener)
|
||||
### emitter.once(event, listener)
|
||||
|
||||
Adds a **one time** listener for the event. This listener is
|
||||
invoked only the next time the event is fired, after which
|
||||
@@ -43,7 +45,7 @@ it is removed.
|
||||
console.log('Ah, we have our first user!');
|
||||
});
|
||||
|
||||
#### emitter.removeListener(event, listener)
|
||||
### emitter.removeListener(event, listener)
|
||||
|
||||
Remove a listener from the listener array for the specified event.
|
||||
**Caution**: changes array indices in the listener array behind the listener.
|
||||
@@ -56,12 +58,12 @@ Remove a listener from the listener array for the specified event.
|
||||
server.removeListener('connection', callback);
|
||||
|
||||
|
||||
#### emitter.removeAllListeners([event])
|
||||
### emitter.removeAllListeners([event])
|
||||
|
||||
Removes all listeners, or those of the specified event.
|
||||
|
||||
|
||||
#### emitter.setMaxListeners(n)
|
||||
### emitter.setMaxListeners(n)
|
||||
|
||||
By default EventEmitters will print a warning if more than 10 listeners are
|
||||
added for a particular event. This is a useful default which helps finding memory leaks.
|
||||
@@ -69,7 +71,7 @@ Obviously not all Emitters should be limited to 10. This function allows
|
||||
that to be increased. Set to zero for unlimited.
|
||||
|
||||
|
||||
#### emitter.listeners(event)
|
||||
### emitter.listeners(event)
|
||||
|
||||
Returns an array of listeners for the specified event. This array can be
|
||||
manipulated, e.g. to remove listeners.
|
||||
@@ -79,12 +81,13 @@ manipulated, e.g. to remove listeners.
|
||||
});
|
||||
console.log(util.inspect(server.listeners('connection'))); // [ [Function] ]
|
||||
|
||||
#### emitter.emit(event, [arg1], [arg2], [...])
|
||||
### emitter.emit(event, [arg1], [arg2], [...])
|
||||
|
||||
Execute each of the listeners in order with the supplied arguments.
|
||||
|
||||
#### Event: 'newListener'
|
||||
### Event: 'newListener'
|
||||
|
||||
`function (event, listener) { }`
|
||||
* `event` {String} The event name
|
||||
* `listener` {Function} The event handler function
|
||||
|
||||
This event is emitted any time someone adds a new listener.
|
||||
+93
-90
@@ -1,4 +1,4 @@
|
||||
## File System
|
||||
# File System
|
||||
|
||||
File I/O is provided by simple wrappers around standard POSIX functions. To
|
||||
use this module do `require('fs')`. All the methods have asynchronous and
|
||||
@@ -58,195 +58,195 @@ the entire process until they complete--halting all connections.
|
||||
Relative path to filename can be used, remember however that this path will be relative
|
||||
to `process.cwd()`.
|
||||
|
||||
### fs.rename(path1, path2, [callback])
|
||||
## fs.rename(path1, path2, [callback])
|
||||
|
||||
Asynchronous rename(2). No arguments other than a possible exception are given
|
||||
to the completion callback.
|
||||
|
||||
### fs.renameSync(path1, path2)
|
||||
## fs.renameSync(path1, path2)
|
||||
|
||||
Synchronous rename(2).
|
||||
|
||||
### fs.truncate(fd, len, [callback])
|
||||
## fs.truncate(fd, len, [callback])
|
||||
|
||||
Asynchronous ftruncate(2). No arguments other than a possible exception are
|
||||
given to the completion callback.
|
||||
|
||||
### fs.truncateSync(fd, len)
|
||||
## fs.truncateSync(fd, len)
|
||||
|
||||
Synchronous ftruncate(2).
|
||||
|
||||
### fs.chown(path, uid, gid, [callback])
|
||||
## fs.chown(path, uid, gid, [callback])
|
||||
|
||||
Asynchronous chown(2). No arguments other than a possible exception are given
|
||||
to the completion callback.
|
||||
|
||||
### fs.chownSync(path, uid, gid)
|
||||
## fs.chownSync(path, uid, gid)
|
||||
|
||||
Synchronous chown(2).
|
||||
|
||||
### fs.fchown(fd, uid, gid, [callback])
|
||||
## fs.fchown(fd, uid, gid, [callback])
|
||||
|
||||
Asynchronous fchown(2). No arguments other than a possible exception are given
|
||||
to the completion callback.
|
||||
|
||||
### fs.fchownSync(fd, uid, gid)
|
||||
## fs.fchownSync(fd, uid, gid)
|
||||
|
||||
Synchronous fchown(2).
|
||||
|
||||
### fs.lchown(path, uid, gid, [callback])
|
||||
## fs.lchown(path, uid, gid, [callback])
|
||||
|
||||
Asynchronous lchown(2). No arguments other than a possible exception are given
|
||||
to the completion callback.
|
||||
|
||||
### fs.lchownSync(path, uid, gid)
|
||||
## fs.lchownSync(path, uid, gid)
|
||||
|
||||
Synchronous lchown(2).
|
||||
|
||||
### fs.chmod(path, mode, [callback])
|
||||
## fs.chmod(path, mode, [callback])
|
||||
|
||||
Asynchronous chmod(2). No arguments other than a possible exception are given
|
||||
to the completion callback.
|
||||
|
||||
### fs.chmodSync(path, mode)
|
||||
## fs.chmodSync(path, mode)
|
||||
|
||||
Synchronous chmod(2).
|
||||
|
||||
### fs.fchmod(fd, mode, [callback])
|
||||
## fs.fchmod(fd, mode, [callback])
|
||||
|
||||
Asynchronous fchmod(2). No arguments other than a possible exception
|
||||
are given to the completion callback.
|
||||
|
||||
### fs.fchmodSync(fd, mode)
|
||||
## fs.fchmodSync(fd, mode)
|
||||
|
||||
Synchronous fchmod(2).
|
||||
|
||||
### fs.lchmod(path, mode, [callback])
|
||||
## fs.lchmod(path, mode, [callback])
|
||||
|
||||
Asynchronous lchmod(2). No arguments other than a possible exception
|
||||
are given to the completion callback.
|
||||
|
||||
### fs.lchmodSync(path, mode)
|
||||
## fs.lchmodSync(path, mode)
|
||||
|
||||
Synchronous lchmod(2).
|
||||
|
||||
### fs.stat(path, [callback])
|
||||
## fs.stat(path, [callback])
|
||||
|
||||
Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
|
||||
`stats` is a [fs.Stats](#fs.Stats) object. See the [fs.Stats](#fs.Stats)
|
||||
section below for more information.
|
||||
|
||||
### fs.lstat(path, [callback])
|
||||
## fs.lstat(path, [callback])
|
||||
|
||||
Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where
|
||||
`stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if
|
||||
`path` is a symbolic link, then the link itself is stat-ed, not the file that it
|
||||
refers to.
|
||||
|
||||
### fs.fstat(fd, [callback])
|
||||
## fs.fstat(fd, [callback])
|
||||
|
||||
Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where
|
||||
`stats` is a `fs.Stats` object. `fstat()` is identical to `stat()`, except that
|
||||
the file to be stat-ed is specified by the file descriptor `fd`.
|
||||
|
||||
### fs.statSync(path)
|
||||
## fs.statSync(path)
|
||||
|
||||
Synchronous stat(2). Returns an instance of `fs.Stats`.
|
||||
|
||||
### fs.lstatSync(path)
|
||||
## fs.lstatSync(path)
|
||||
|
||||
Synchronous lstat(2). Returns an instance of `fs.Stats`.
|
||||
|
||||
### fs.fstatSync(fd)
|
||||
## fs.fstatSync(fd)
|
||||
|
||||
Synchronous fstat(2). Returns an instance of `fs.Stats`.
|
||||
|
||||
### fs.link(srcpath, dstpath, [callback])
|
||||
## fs.link(srcpath, dstpath, [callback])
|
||||
|
||||
Asynchronous link(2). No arguments other than a possible exception are given to
|
||||
the completion callback.
|
||||
|
||||
### fs.linkSync(srcpath, dstpath)
|
||||
## fs.linkSync(srcpath, dstpath)
|
||||
|
||||
Synchronous link(2).
|
||||
|
||||
### fs.symlink(linkdata, path, [type], [callback])
|
||||
## fs.symlink(linkdata, path, [type], [callback])
|
||||
|
||||
Asynchronous symlink(2). No arguments other than a possible exception are given
|
||||
to the completion callback.
|
||||
`type` argument can be either `'dir'` or `'file'` (default is `'file'`). It is only
|
||||
used on Windows (ignored on other platforms).
|
||||
|
||||
### fs.symlinkSync(linkdata, path, [type])
|
||||
## fs.symlinkSync(linkdata, path, [type])
|
||||
|
||||
Synchronous symlink(2).
|
||||
|
||||
### fs.readlink(path, [callback])
|
||||
## fs.readlink(path, [callback])
|
||||
|
||||
Asynchronous readlink(2). The callback gets two arguments `(err,
|
||||
linkString)`.
|
||||
|
||||
### fs.readlinkSync(path)
|
||||
## fs.readlinkSync(path)
|
||||
|
||||
Synchronous readlink(2). Returns the symbolic link's string value.
|
||||
|
||||
### fs.realpath(path, [callback])
|
||||
## fs.realpath(path, [callback])
|
||||
|
||||
Asynchronous realpath(2). The callback gets two arguments `(err,
|
||||
resolvedPath)`. May use `process.cwd` to resolve relative paths.
|
||||
|
||||
### fs.realpathSync(path)
|
||||
## fs.realpathSync(path)
|
||||
|
||||
Synchronous realpath(2). Returns the resolved path.
|
||||
|
||||
### fs.unlink(path, [callback])
|
||||
## fs.unlink(path, [callback])
|
||||
|
||||
Asynchronous unlink(2). No arguments other than a possible exception are given
|
||||
to the completion callback.
|
||||
|
||||
### fs.unlinkSync(path)
|
||||
## fs.unlinkSync(path)
|
||||
|
||||
Synchronous unlink(2).
|
||||
|
||||
### fs.rmdir(path, [callback])
|
||||
## fs.rmdir(path, [callback])
|
||||
|
||||
Asynchronous rmdir(2). No arguments other than a possible exception are given
|
||||
to the completion callback.
|
||||
|
||||
### fs.rmdirSync(path)
|
||||
## fs.rmdirSync(path)
|
||||
|
||||
Synchronous rmdir(2).
|
||||
|
||||
### fs.mkdir(path, [mode], [callback])
|
||||
## fs.mkdir(path, [mode], [callback])
|
||||
|
||||
Asynchronous mkdir(2). No arguments other than a possible exception are given
|
||||
to the completion callback. `mode` defaults to `0777`.
|
||||
|
||||
### fs.mkdirSync(path, [mode])
|
||||
## fs.mkdirSync(path, [mode])
|
||||
|
||||
Synchronous mkdir(2).
|
||||
|
||||
### fs.readdir(path, [callback])
|
||||
## fs.readdir(path, [callback])
|
||||
|
||||
Asynchronous readdir(3). Reads the contents of a directory.
|
||||
The callback gets two arguments `(err, files)` where `files` is an array of
|
||||
the names of the files in the directory excluding `'.'` and `'..'`.
|
||||
|
||||
### fs.readdirSync(path)
|
||||
## fs.readdirSync(path)
|
||||
|
||||
Synchronous readdir(3). Returns an array of filenames excluding `'.'` and
|
||||
`'..'`.
|
||||
|
||||
### fs.close(fd, [callback])
|
||||
## fs.close(fd, [callback])
|
||||
|
||||
Asynchronous close(2). No arguments other than a possible exception are given
|
||||
to the completion callback.
|
||||
|
||||
### fs.closeSync(fd)
|
||||
## fs.closeSync(fd)
|
||||
|
||||
Synchronous close(2).
|
||||
|
||||
### fs.open(path, flags, [mode], [callback])
|
||||
## fs.open(path, flags, [mode], [callback])
|
||||
|
||||
Asynchronous file open. See open(2). `flags` can be:
|
||||
|
||||
@@ -282,31 +282,31 @@ Exclusive mode (`O_EXCL`) ensures that `path` is newly created. `fs.open()`
|
||||
fails if a file by that name already exists. On POSIX systems, symlinks are
|
||||
not followed. Exclusive mode may or may not work with network file systems.
|
||||
|
||||
### fs.openSync(path, flags, [mode])
|
||||
## fs.openSync(path, flags, [mode])
|
||||
|
||||
Synchronous open(2).
|
||||
|
||||
### fs.utimes(path, atime, mtime, [callback])
|
||||
### fs.utimesSync(path, atime, mtime)
|
||||
## fs.utimes(path, atime, mtime, [callback])
|
||||
## fs.utimesSync(path, atime, mtime)
|
||||
|
||||
Change file timestamps of the file referenced by the supplied path.
|
||||
|
||||
### fs.futimes(fd, atime, mtime, [callback])
|
||||
### fs.futimesSync(fd, atime, mtime)
|
||||
## fs.futimes(fd, atime, mtime, [callback])
|
||||
## fs.futimesSync(fd, atime, mtime)
|
||||
|
||||
Change the file timestamps of a file referenced by the supplied file
|
||||
descriptor.
|
||||
|
||||
### fs.fsync(fd, [callback])
|
||||
## fs.fsync(fd, [callback])
|
||||
|
||||
Asynchronous fsync(2). No arguments other than a possible exception are given
|
||||
to the completion callback.
|
||||
|
||||
### fs.fsyncSync(fd)
|
||||
## fs.fsyncSync(fd)
|
||||
|
||||
Synchronous fsync(2).
|
||||
|
||||
### fs.write(fd, buffer, offset, length, position, [callback])
|
||||
## fs.write(fd, buffer, offset, length, position, [callback])
|
||||
|
||||
Write `buffer` to the file specified by `fd`.
|
||||
|
||||
@@ -324,17 +324,17 @@ Note that it is unsafe to use `fs.write` multiple times on the same file
|
||||
without waiting for the callback. For this scenario,
|
||||
`fs.createWriteStream` is strongly recommended.
|
||||
|
||||
### fs.writeSync(fd, buffer, offset, length, position)
|
||||
## fs.writeSync(fd, buffer, offset, length, position)
|
||||
|
||||
Synchronous version of buffer-based `fs.write()`. Returns the number of bytes
|
||||
written.
|
||||
|
||||
### fs.writeSync(fd, str, position, [encoding])
|
||||
## fs.writeSync(fd, str, position, [encoding])
|
||||
|
||||
Synchronous version of string-based `fs.write()`. `encoding` defaults to
|
||||
`'utf8'`. Returns the number of _bytes_ written.
|
||||
|
||||
### fs.read(fd, buffer, offset, length, position, [callback])
|
||||
## fs.read(fd, buffer, offset, length, position, [callback])
|
||||
|
||||
Read data from the file specified by `fd`.
|
||||
|
||||
@@ -349,17 +349,17 @@ If `position` is `null`, data will be read from the current file position.
|
||||
|
||||
The callback is given the three arguments, `(err, bytesRead, buffer)`.
|
||||
|
||||
### fs.readSync(fd, buffer, offset, length, position)
|
||||
## fs.readSync(fd, buffer, offset, length, position)
|
||||
|
||||
Synchronous version of buffer-based `fs.read`. Returns the number of
|
||||
`bytesRead`.
|
||||
|
||||
### fs.readSync(fd, length, position, encoding)
|
||||
## fs.readSync(fd, length, position, encoding)
|
||||
|
||||
Synchronous version of string-based `fs.read`. Returns the number of
|
||||
`bytesRead`.
|
||||
|
||||
### fs.readFile(filename, [encoding], [callback])
|
||||
## fs.readFile(filename, [encoding], [callback])
|
||||
|
||||
Asynchronously reads the entire contents of a file. Example:
|
||||
|
||||
@@ -374,7 +374,7 @@ contents of the file.
|
||||
If no encoding is specified, then the raw buffer is returned.
|
||||
|
||||
|
||||
### fs.readFileSync(filename, [encoding])
|
||||
## fs.readFileSync(filename, [encoding])
|
||||
|
||||
Synchronous version of `fs.readFile`. Returns the contents of the `filename`.
|
||||
|
||||
@@ -382,7 +382,7 @@ If `encoding` is specified then this function returns a string. Otherwise it
|
||||
returns a buffer.
|
||||
|
||||
|
||||
### fs.writeFile(filename, data, [encoding], [callback])
|
||||
## fs.writeFile(filename, data, [encoding], [callback])
|
||||
|
||||
Asynchronously writes data to a file, replacing the file if it already exists.
|
||||
`data` can be a string or a buffer. The `encoding` argument is ignored if
|
||||
@@ -395,11 +395,11 @@ Example:
|
||||
console.log('It\'s saved!');
|
||||
});
|
||||
|
||||
### fs.writeFileSync(filename, data, [encoding])
|
||||
## fs.writeFileSync(filename, data, [encoding])
|
||||
|
||||
The synchronous version of `fs.writeFile`.
|
||||
|
||||
### fs.appendFile(filename, data, encoding='utf8', [callback])
|
||||
## fs.appendFile(filename, data, encoding='utf8', [callback])
|
||||
|
||||
Asynchronously append data to a file, creating the file if it not yet exists.
|
||||
`data` can be a string or a buffer. The `encoding` argument is ignored if
|
||||
@@ -412,11 +412,11 @@ Example:
|
||||
console.log('The "data to append" was appended to file!');
|
||||
});
|
||||
|
||||
### fs.appendFileSync(filename, data, encoding='utf8')
|
||||
## fs.appendFileSync(filename, data, encoding='utf8')
|
||||
|
||||
The synchronous version of `fs.appendFile`.
|
||||
|
||||
### fs.watchFile(filename, [options], listener)
|
||||
## fs.watchFile(filename, [options], listener)
|
||||
|
||||
Watch for changes on `filename`. The callback `listener` will be called each
|
||||
time the file is accessed.
|
||||
@@ -442,11 +442,11 @@ If you want to be notified when the file was modified, not just accessed
|
||||
you need to compare `curr.mtime` and `prev.mtime`.
|
||||
|
||||
|
||||
### fs.unwatchFile(filename)
|
||||
## fs.unwatchFile(filename)
|
||||
|
||||
Stop watching for changes on `filename`.
|
||||
|
||||
### fs.watch(filename, [options], listener)
|
||||
## fs.watch(filename, [options], listener)
|
||||
|
||||
Watch for changes on `filename`, where `filename` is either a file or a
|
||||
directory. The returned object is [fs.FSWatcher](#fs.FSWatcher).
|
||||
@@ -476,7 +476,7 @@ callback, and have some fallback logic if it is null.
|
||||
}
|
||||
});
|
||||
|
||||
### fs.exists(p, [callback])
|
||||
## fs.exists(p, [callback])
|
||||
|
||||
Test whether or not the given path exists by checking with the file system.
|
||||
Then call the `callback` argument with either true or false. Example:
|
||||
@@ -486,11 +486,11 @@ Then call the `callback` argument with either true or false. Example:
|
||||
});
|
||||
|
||||
|
||||
### fs.existsSync(p)
|
||||
## fs.existsSync(p)
|
||||
|
||||
Synchronous version of `fs.exists`.
|
||||
|
||||
## fs.Stats
|
||||
## Class: fs.Stats
|
||||
|
||||
Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their
|
||||
synchronous counterparts are of this type.
|
||||
@@ -533,17 +533,8 @@ be found in the [MDN JavaScript Reference][MDN-Date] page.
|
||||
[MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
|
||||
[MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime
|
||||
|
||||
## fs.ReadStream
|
||||
|
||||
`ReadStream` is a [Readable Stream](streams.html#readable_Stream).
|
||||
|
||||
### Event: 'open'
|
||||
|
||||
`function (fd) { }`
|
||||
|
||||
`fd` is the file descriptor used by the ReadStream.
|
||||
|
||||
### fs.createReadStream(path, [options])
|
||||
## fs.createReadStream(path, [options])
|
||||
|
||||
Returns a new ReadStream object (See `Readable Stream`).
|
||||
|
||||
@@ -565,22 +556,18 @@ An example to read the last 10 bytes of a file which is 100 bytes long:
|
||||
fs.createReadStream('sample.txt', {start: 90, end: 99});
|
||||
|
||||
|
||||
## fs.WriteStream
|
||||
## Class: fs.ReadStream
|
||||
|
||||
`WriteStream` is a [Writable Stream](streams.html#writable_Stream).
|
||||
`ReadStream` is a [Readable Stream](stream.html#readable_stream).
|
||||
|
||||
### Event: 'open'
|
||||
|
||||
`function (fd) { }`
|
||||
|
||||
`fd` is the file descriptor used by the WriteStream.
|
||||
`fd` is the file descriptor used by the ReadStream.
|
||||
|
||||
### file.bytesWritten
|
||||
|
||||
The number of bytes written so far. Does not include data that is still queued
|
||||
for writing.
|
||||
|
||||
### fs.createWriteStream(path, [options])
|
||||
## fs.createWriteStream(path, [options])
|
||||
|
||||
Returns a new WriteStream object (See `Writable Stream`).
|
||||
|
||||
@@ -595,22 +582,38 @@ some position past the beginning of the file. Modifying a file rather
|
||||
than replacing it may require a `flags` mode of `r+` rather than the
|
||||
default mode `w`.
|
||||
|
||||
## fs.FSWatcher
|
||||
## fs.WriteStream
|
||||
|
||||
`WriteStream` is a [Writable Stream](stream.html#writable_stream).
|
||||
|
||||
### Event: 'open'
|
||||
|
||||
`function (fd) { }`
|
||||
|
||||
`fd` is the file descriptor used by the WriteStream.
|
||||
|
||||
### file.bytesWritten
|
||||
|
||||
The number of bytes written so far. Does not include data that is still queued
|
||||
for writing.
|
||||
|
||||
## Class: fs.FSWatcher
|
||||
|
||||
Objects returned from `fs.watch()` are of this type.
|
||||
|
||||
#### watcher.close()
|
||||
### watcher.close()
|
||||
|
||||
Stop watching for changes on the given `fs.FSWatcher`.
|
||||
|
||||
#### Event: 'change'
|
||||
### Event: 'change'
|
||||
|
||||
`function (event, filename) {}`
|
||||
* `event` {String} The type of fs change
|
||||
* `filename` {String} The filename that changed (if relevant/available)
|
||||
|
||||
Emitted when something changes in a watched directory or file.
|
||||
See more details in [fs.watch](#fs.watch).
|
||||
|
||||
#### Event: 'error'
|
||||
### Event: 'error'
|
||||
|
||||
`function (exception) {}`
|
||||
|
||||
|
||||
+55
-16
@@ -1,30 +1,50 @@
|
||||
## Global Objects
|
||||
# Global Objects
|
||||
|
||||
<!-- type=misc -->
|
||||
|
||||
These objects are available in all modules. Some of these objects aren't
|
||||
actually in the global scope but in the module scope - this will be noted.
|
||||
|
||||
### global
|
||||
## global
|
||||
|
||||
The global namespace object.
|
||||
<!-- type=global -->
|
||||
|
||||
* {Object} The global namespace object.
|
||||
|
||||
In browsers, the top-level scope is the global scope. That means that in
|
||||
browsers if you're in the global scope `var something` will define a global
|
||||
variable. In Node this is different. The top-level scope is not the global
|
||||
scope; `var something` inside a Node module will be local to that module.
|
||||
|
||||
### process
|
||||
## process
|
||||
|
||||
<!-- type=global -->
|
||||
|
||||
* {Object}
|
||||
|
||||
The process object. See the [process object](process.html#process) section.
|
||||
|
||||
### console
|
||||
## console
|
||||
|
||||
<!-- type=global -->
|
||||
|
||||
* {Object}
|
||||
|
||||
Used to print to stdout and stderr. See the [stdio](stdio.html) section.
|
||||
|
||||
### Buffer
|
||||
## Buffer
|
||||
|
||||
Used to handle binary data. See the [buffers](buffers.html) section.
|
||||
<!-- type=global -->
|
||||
|
||||
### require()
|
||||
* {Object}
|
||||
|
||||
Used to handle binary data. See the [buffer section](buffer.html).
|
||||
|
||||
## require()
|
||||
|
||||
<!-- type=var -->
|
||||
|
||||
* {Function}
|
||||
|
||||
To require modules. See the [Modules](modules.html#modules) section.
|
||||
`require` isn't actually a global but rather local to each module.
|
||||
@@ -37,11 +57,16 @@ but rather than loading the module, just return the resolved filename.
|
||||
|
||||
### require.cache
|
||||
|
||||
* {Object}
|
||||
|
||||
Modules are cached in this object when they are required. By deleting a key
|
||||
value from this object, the next `require` will reload the module.
|
||||
|
||||
## __filename
|
||||
|
||||
### __filename
|
||||
<!-- type=var -->
|
||||
|
||||
* {String}
|
||||
|
||||
The filename of the code being executed. This is the resolved absolute path
|
||||
of this code file. For a main program this is not necessarily the same
|
||||
@@ -55,7 +80,11 @@ Example: running `node example.js` from `/Users/mjr`
|
||||
|
||||
`__filename` isn't actually a global but rather local to each module.
|
||||
|
||||
### __dirname
|
||||
## __dirname
|
||||
|
||||
<!-- type=var -->
|
||||
|
||||
* {String}
|
||||
|
||||
The name of the directory that the currently executing script resides in.
|
||||
|
||||
@@ -67,7 +96,11 @@ Example: running `node example.js` from `/Users/mjr`
|
||||
`__dirname` isn't actually a global but rather local to each module.
|
||||
|
||||
|
||||
### module
|
||||
## module
|
||||
|
||||
<!-- type=var -->
|
||||
|
||||
* {Object}
|
||||
|
||||
A reference to the current module. In particular
|
||||
`module.exports` is the same as the `exports` object.
|
||||
@@ -77,7 +110,9 @@ See the [module system documentation](modules.html) for more
|
||||
information.
|
||||
|
||||
|
||||
### exports
|
||||
## exports
|
||||
|
||||
<!-- type=var -->
|
||||
|
||||
An object which is shared between all instances of the current module and
|
||||
made accessible through `require()`.
|
||||
@@ -87,9 +122,13 @@ made accessible through `require()`.
|
||||
See the [module system documentation](modules.html) for more
|
||||
information.
|
||||
|
||||
### setTimeout(cb, ms)
|
||||
### clearTimeout(t)
|
||||
### setInterval(cb, ms)
|
||||
### clearInterval(t)
|
||||
See the [module section](modules.html) for more information.
|
||||
|
||||
## setTimeout(cb, ms)
|
||||
## clearTimeout(t)
|
||||
## setInterval(cb, ms)
|
||||
## clearInterval(t)
|
||||
|
||||
<!--type=global-->
|
||||
|
||||
The timer functions are global variables. See the [timers](timers.html) section.
|
||||
+24
-23
@@ -1,4 +1,4 @@
|
||||
## HTTP
|
||||
# HTTP
|
||||
|
||||
To use the HTTP server and client one must `require('http')`.
|
||||
|
||||
@@ -23,7 +23,14 @@ parsing only. It parses a message into headers and body but it does not
|
||||
parse the actual headers or the body.
|
||||
|
||||
|
||||
## http.Server
|
||||
## http.createServer([requestListener])
|
||||
|
||||
Returns a new web server object.
|
||||
|
||||
The `requestListener` is a function which is automatically
|
||||
added to the `'request'` event.
|
||||
|
||||
## Class: http.Server
|
||||
|
||||
This is an `EventEmitter` with the following events:
|
||||
|
||||
@@ -108,13 +115,6 @@ sent to the server on that socket.
|
||||
|
||||
If a client connection emits an 'error' event - it will forwarded here.
|
||||
|
||||
### http.createServer([requestListener])
|
||||
|
||||
Returns a new web server object.
|
||||
|
||||
The `requestListener` is a function which is automatically
|
||||
added to the `'request'` event.
|
||||
|
||||
### server.listen(port, [hostname], [callback])
|
||||
|
||||
Begin accepting connections on the specified port and hostname. If the
|
||||
@@ -149,12 +149,12 @@ Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -
|
||||
no limit will be applied.
|
||||
|
||||
|
||||
## http.ServerRequest
|
||||
## Class: http.ServerRequest
|
||||
|
||||
This object is created internally by a HTTP server -- not by
|
||||
the user -- and passed as the first argument to a `'request'` listener.
|
||||
|
||||
The request implements the [Readable Stream](streams.html#readable_Stream)
|
||||
The request implements the [Readable Stream](stream.html#readable_stream)
|
||||
interface. This is an `EventEmitter` with the following events:
|
||||
|
||||
### Event: 'data'
|
||||
@@ -163,7 +163,7 @@ interface. This is an `EventEmitter` with the following events:
|
||||
|
||||
Emitted when a piece of the message body is received. The chunk is a string if
|
||||
an encoding has been set with `request.setEncoding()`, otherwise it's a
|
||||
[Buffer](buffers.html).
|
||||
[Buffer](buffer.html).
|
||||
|
||||
Note that the __data will be lost__ if there is no listener when a
|
||||
`ServerRequest` emits a `'data'` event.
|
||||
@@ -269,12 +269,12 @@ authentication details.
|
||||
|
||||
|
||||
|
||||
## http.ServerResponse
|
||||
## Class: http.ServerResponse
|
||||
|
||||
This object is created internally by a HTTP server--not by the user. It is
|
||||
passed as the second parameter to the `'request'` event.
|
||||
|
||||
The response implements the [Writable Stream](streams.html#writable_Stream)
|
||||
The response implements the [Writable Stream](stream.html#writable_stream)
|
||||
interface. This is an `EventEmitter` with the following events:
|
||||
|
||||
### Event: 'close'
|
||||
@@ -524,7 +524,7 @@ Example:
|
||||
});
|
||||
|
||||
|
||||
## http.Agent
|
||||
## Class: http.Agent
|
||||
|
||||
In node 0.5.3+ there is a new implementation of the HTTP Agent which is used
|
||||
for pooling sockets used in HTTP client requests.
|
||||
@@ -555,10 +555,6 @@ Alternatively, you could just opt out of pooling entirely using `agent:false`:
|
||||
// Do stuff
|
||||
})
|
||||
|
||||
## http.globalAgent
|
||||
|
||||
Global instance of Agent which is used as the default for all http client requests.
|
||||
|
||||
### agent.maxSockets
|
||||
|
||||
By default set to 5. Determines how many concurrent sockets the agent can have
|
||||
@@ -574,8 +570,13 @@ modify.
|
||||
An object which contains queues of requests that have not yet been assigned to
|
||||
sockets. Do not modify.
|
||||
|
||||
## http.globalAgent
|
||||
|
||||
## http.ClientRequest
|
||||
Global instance of Agent which is used as the default for all http client
|
||||
requests.
|
||||
|
||||
|
||||
## Class: http.ClientRequest
|
||||
|
||||
This object is created internally and returned from `http.request()`. It
|
||||
represents an _in-progress_ request whose header has already been queued. The
|
||||
@@ -615,7 +616,7 @@ event, the entire body will be caught.
|
||||
Note: Node does not check whether Content-Length and the length of the body
|
||||
which has been transmitted are equal or not.
|
||||
|
||||
The request implements the [Writable Stream](streams.html#writable_Stream)
|
||||
The request implements the [Writable Stream](stream.html#writable_stream)
|
||||
interface. This is an `EventEmitter` with the following events:
|
||||
|
||||
### Event 'response'
|
||||
@@ -765,7 +766,7 @@ server--in that case it is suggested to use the
|
||||
`['Transfer-Encoding', 'chunked']` header line when
|
||||
creating the request.
|
||||
|
||||
The `chunk` argument should be a [buffer](buffers.html) or a string.
|
||||
The `chunk` argument should be a [buffer](buffer.html) or a string.
|
||||
|
||||
The `encoding` argument is optional and only applies when `chunk` is a string.
|
||||
Defaults to `'utf8'`.
|
||||
@@ -807,7 +808,7 @@ will be called.
|
||||
This object is created when making a request with `http.request()`. It is
|
||||
passed to the `'response'` event of the request object.
|
||||
|
||||
The response implements the [Readable Stream](streams.html#readable_Stream)
|
||||
The response implements the [Readable Stream](stream.html#readable_stream)
|
||||
interface. This is an `EventEmitter` with the following events:
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
## HTTPS
|
||||
# HTTPS
|
||||
|
||||
HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a
|
||||
separate module.
|
||||
|
||||
## https.Server
|
||||
## Class: https.Server
|
||||
|
||||
This class is a subclass of `tls.Server` and emits events same as
|
||||
`http.Server`. See `http.Server` for more information.
|
||||
@@ -159,7 +159,7 @@ Example:
|
||||
});
|
||||
|
||||
|
||||
## https.Agent
|
||||
## Class: https.Agent
|
||||
|
||||
An Agent object for HTTPS similar to [http.Agent](http.html#http.Agent).
|
||||
See [https.request()](#https.request) for more information.
|
||||
|
||||
+93
-12
@@ -1,4 +1,6 @@
|
||||
## Modules
|
||||
# Modules
|
||||
|
||||
<!--name=module-->
|
||||
|
||||
Node has a simple module loading system. In Node, files and modules are in
|
||||
one-to-one correspondence. As an example, `foo.js` loads the module
|
||||
@@ -30,7 +32,11 @@ Variables
|
||||
local to the module will be private. In this example the variable `PI` is
|
||||
private to `circle.js`.
|
||||
|
||||
### Cycles
|
||||
The module system is implemented in the `require("module")` module.
|
||||
|
||||
## Cycles
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
When there are circular `require()` calls, a module might not be
|
||||
done being executed when it is returned.
|
||||
@@ -84,7 +90,9 @@ The output of this program would thus be:
|
||||
If you have cyclic module dependencies in your program, make sure to
|
||||
plan accordingly.
|
||||
|
||||
### Core Modules
|
||||
## Core Modules
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
Node has several modules compiled into the binary. These modules are
|
||||
described in greater detail elsewhere in this documentation.
|
||||
@@ -95,7 +103,9 @@ Core modules are always preferentially loaded if their identifier is
|
||||
passed to `require()`. For instance, `require('http')` will always
|
||||
return the built in HTTP module, even if there is a file by that name.
|
||||
|
||||
### File Modules
|
||||
## File Modules
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
If the exact filename is not found, then node will attempt to load the
|
||||
required filename with the added extension of `.js`, `.json`, and then `.node`.
|
||||
@@ -118,7 +128,9 @@ Without a leading '/' or './' to indicate a file, the module is either a
|
||||
If the given path does not exist, `require()` will throw an Error with its
|
||||
`code` property set to `'MODULE_NOT_FOUND'`.
|
||||
|
||||
### Loading from `node_modules` Folders
|
||||
## Loading from `node_modules` Folders
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
If the module identifier passed to `require()` is not a native module,
|
||||
and does not begin with `'/'`, `'../'`, or `'./'`, then node starts at the
|
||||
@@ -140,7 +152,9 @@ this order:
|
||||
This allows programs to localize their dependencies, so that they do not
|
||||
clash.
|
||||
|
||||
### Folders as Modules
|
||||
## Folders as Modules
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
It is convenient to organize programs and libraries into self-contained
|
||||
directories, and then provide a single entry point to that library.
|
||||
@@ -168,7 +182,9 @@ example, then `require('./some-library')` would attempt to load:
|
||||
* `./some-library/index.js`
|
||||
* `./some-library/index.node`
|
||||
|
||||
### Caching
|
||||
## Caching
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
Modules are cached after the first time they are loaded. This means
|
||||
(among other things) that every call to `require('foo')` will get
|
||||
@@ -182,7 +198,9 @@ dependencies to be loaded even when they would cause cycles.
|
||||
If you want to have a module execute code multiple times, then export a
|
||||
function, and call that function.
|
||||
|
||||
#### Module Caching Caveats
|
||||
### Module Caching Caveats
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
Modules are cached based on their resolved filename. Since modules may
|
||||
resolve to a different filename based on the location of the calling
|
||||
@@ -190,8 +208,22 @@ module (loading from `node_modules` folders), it is not a *guarantee*
|
||||
that `require('foo')` will always return the exact same object, if it
|
||||
would resolve to different files.
|
||||
|
||||
## The `module` Object
|
||||
|
||||
<!-- type=var -->
|
||||
<!-- name=module -->
|
||||
|
||||
* {Object}
|
||||
|
||||
In each module, the `module` free variable is a reference to the object
|
||||
representing the current module. In particular
|
||||
`module.exports` is the same as the `exports` object.
|
||||
`module` isn't actually a global but rather local to each module.
|
||||
|
||||
### module.exports
|
||||
|
||||
* {Object}
|
||||
|
||||
The `exports` object is created by the Module system. Sometimes this is not
|
||||
acceptable, many want their module to be an instance of some class. To do this
|
||||
assign the desired export object to `module.exports`. For example suppose we
|
||||
@@ -230,7 +262,10 @@ y.js:
|
||||
console.log(x.a);
|
||||
|
||||
|
||||
### module.require
|
||||
### module.require(id)
|
||||
|
||||
* `id` {String}
|
||||
* Return: {Object} `exports` from the resolved module
|
||||
|
||||
The `module.require` method provides a way to load a module as if
|
||||
`require()` was called from the original module.
|
||||
@@ -241,7 +276,47 @@ typically *only* available within a specific module's code, it must be
|
||||
explicitly exported in order to be used.
|
||||
|
||||
|
||||
### All Together...
|
||||
### module.id
|
||||
|
||||
* {String}
|
||||
|
||||
The identifier for the module. Typically this is the fully resolved
|
||||
filename.
|
||||
|
||||
|
||||
### module.filename
|
||||
|
||||
* {String}
|
||||
|
||||
The fully resolved filename to the module.
|
||||
|
||||
|
||||
### module.loaded
|
||||
|
||||
* {Boolean}
|
||||
|
||||
Whether or not the module is done loading, or is in the process of
|
||||
loading.
|
||||
|
||||
|
||||
### module.parent
|
||||
|
||||
* {Module Object}
|
||||
|
||||
The module that required this one.
|
||||
|
||||
|
||||
### module.children
|
||||
|
||||
* {Array}
|
||||
|
||||
The module objects required by this one.
|
||||
|
||||
|
||||
|
||||
## All Together...
|
||||
|
||||
<!-- type=misc -->
|
||||
|
||||
To get the exact filename that will be loaded when `require()` is called, use
|
||||
the `require.resolve()` function.
|
||||
@@ -290,7 +365,9 @@ in pseudocode of what require.resolve does:
|
||||
c. let I = I - 1
|
||||
6. return DIRS
|
||||
|
||||
### Loading from the global folders
|
||||
## Loading from the global folders
|
||||
|
||||
<!-- type=misc -->
|
||||
|
||||
If the `NODE_PATH` environment variable is set to a colon-delimited list
|
||||
of absolute paths, then node will search those paths for modules if they
|
||||
@@ -310,7 +387,9 @@ These are mostly for historic reasons. You are highly encouraged to
|
||||
place your dependencies locally in `node_modules` folders. They will be
|
||||
loaded faster, and more reliably.
|
||||
|
||||
### Accessing the main module
|
||||
## Accessing the main module
|
||||
|
||||
<!-- type=misc -->
|
||||
|
||||
When a file is run directly from Node, `require.main` is set to its
|
||||
`module`. That means that you can determine whether a file has been run
|
||||
@@ -327,6 +406,8 @@ by checking `require.main.filename`.
|
||||
|
||||
## Addenda: Package Manager Tips
|
||||
|
||||
<!-- type=misc -->
|
||||
|
||||
The semantics of Node's `require()` function were designed to be general
|
||||
enough to support a number of sane directory structures. Package manager
|
||||
programs such as `dpkg`, `rpm`, and `npm` will hopefully find it possible to
|
||||
|
||||
+50
-57
@@ -1,10 +1,10 @@
|
||||
## net
|
||||
# net
|
||||
|
||||
The `net` module provides you with an asynchronous network wrapper. It contains
|
||||
methods for creating both servers and clients (called streams). You can include
|
||||
this module with `require('net');`
|
||||
|
||||
### net.createServer([options], [connectionListener])
|
||||
## net.createServer([options], [connectionListener])
|
||||
|
||||
Creates a new TCP server. The `connectionListener` argument is
|
||||
automatically set as a listener for the ['connection'](#event_connection_)
|
||||
@@ -49,8 +49,8 @@ Use `nc` to connect to a UNIX domain socket server:
|
||||
|
||||
nc -U /tmp/echo.sock
|
||||
|
||||
### net.connect(options, [cnnectionListener])
|
||||
### net.createConnection(options, [cnnectionListener])
|
||||
## net.connect(options, [cnnectionListener])
|
||||
## net.createConnection(options, [cnnectionListener])
|
||||
|
||||
Constructs a new socket object and opens the socket to the given location.
|
||||
When the socket is established, the ['connect'](#event_connect_) event will be
|
||||
@@ -97,29 +97,27 @@ changed to
|
||||
|
||||
var client = net.connect({path: '/tmp/echo.sock'},
|
||||
|
||||
### net.connect(port, [host], [connectListener])
|
||||
### net.createConnection(port, [host], [connectListener])
|
||||
## net.connect(port, [host], [connectListener])
|
||||
## net.createConnection(port, [host], [connectListener])
|
||||
|
||||
Creates a TCP connection to `port` on `host`. If `host` is omitted,
|
||||
`'localhost'` will be assumed.
|
||||
The `connectListener` parameter will be added as an listener for the
|
||||
['connect'](#event_connect_) event.
|
||||
|
||||
### net.connect(path, [connectListener])
|
||||
### net.createConnection(path, [connectListener])
|
||||
## net.connect(path, [connectListener])
|
||||
## net.createConnection(path, [connectListener])
|
||||
|
||||
Creates unix socket connection to `path`.
|
||||
The `connectListener` parameter will be added as an listener for the
|
||||
['connect'](#event_connect_) event.
|
||||
|
||||
---
|
||||
|
||||
### net.Server
|
||||
## Class: net.Server
|
||||
|
||||
This class is used to create a TCP or UNIX server.
|
||||
A server is a `net.Socket` that can listen for new incoming connections.
|
||||
|
||||
#### server.listen(port, [host], [listeningListener])
|
||||
### server.listen(port, [host], [listeningListener])
|
||||
|
||||
Begin accepting connections on the specified `port` and `host`. If the
|
||||
`host` is omitted, the server will accept connections directed to any
|
||||
@@ -147,7 +145,7 @@ would be to wait a second and then try again. This can be done with
|
||||
(Note: All sockets in Node set `SO_REUSEADDR` already)
|
||||
|
||||
|
||||
#### server.listen(path, [listeningListener])
|
||||
### server.listen(path, [listeningListener])
|
||||
|
||||
Start a UNIX socket server listening for connections on the given `path`.
|
||||
|
||||
@@ -156,14 +154,14 @@ This function is asynchronous. When the server has been bound,
|
||||
the last parameter `listeningListener` will be added as an listener for the
|
||||
['listening'](#event_listening_) event.
|
||||
|
||||
#### server.close([cb])
|
||||
### server.close([cb])
|
||||
|
||||
Stops the server from accepting new connections. This function is
|
||||
asynchronous, the server is finally closed when the server emits a `'close'`
|
||||
event. Optionally, you can pass a callback to listen for the `'close'` event.
|
||||
|
||||
|
||||
#### server.address()
|
||||
### server.address()
|
||||
|
||||
Returns the bound address and port of the server as reported by the operating system.
|
||||
Useful to find which port was assigned when giving getting an OS-assigned address.
|
||||
@@ -183,54 +181,52 @@ Example:
|
||||
|
||||
Don't call `server.address()` until the `'listening'` event has been emitted.
|
||||
|
||||
#### server.maxConnections
|
||||
### server.maxConnections
|
||||
|
||||
Set this property to reject connections when the server's connection count gets
|
||||
high.
|
||||
|
||||
#### server.connections
|
||||
### server.connections
|
||||
|
||||
The number of concurrent connections on the server.
|
||||
|
||||
|
||||
`net.Server` is an `EventEmitter` with the following events:
|
||||
|
||||
#### Event: 'listening'
|
||||
### Event: 'listening'
|
||||
|
||||
`function () {}`
|
||||
|
||||
Emitted when the server has been bound after calling `server.listen`.
|
||||
|
||||
#### Event: 'connection'
|
||||
### Event: 'connection'
|
||||
|
||||
`function (socket) {}`
|
||||
|
||||
Emitted when a new connection is made. `socket` is an instance of
|
||||
`net.Socket`.
|
||||
|
||||
#### Event: 'close'
|
||||
### Event: 'close'
|
||||
|
||||
`function () {}`
|
||||
|
||||
Emitted when the server closes.
|
||||
|
||||
#### Event: 'error'
|
||||
### Event: 'error'
|
||||
|
||||
`function (exception) {}`
|
||||
|
||||
Emitted when an error occurs. The `'close'` event will be called directly
|
||||
following this event. See example in discussion of `server.listen`.
|
||||
|
||||
---
|
||||
|
||||
### net.Socket
|
||||
## Class: net.Socket
|
||||
|
||||
This object is an abstraction of a TCP or UNIX socket. `net.Socket`
|
||||
instances implement a duplex Stream interface. They can be created by the
|
||||
user and used as a client (with `connect()`) or they can be created by Node
|
||||
and passed to the user through the `'connection'` event of a server.
|
||||
|
||||
#### new net.Socket([options])
|
||||
### new net.Socket([options])
|
||||
|
||||
Construct a new socket object.
|
||||
|
||||
@@ -245,8 +241,8 @@ Construct a new socket object.
|
||||
specified underlying protocol. It can be `'tcp4'`, `'tcp6'`, or `'unix'`.
|
||||
About `allowHalfOpen`, refer to `createServer()` and `'end'` event.
|
||||
|
||||
#### socket.connect(port, [host], [connectListener])
|
||||
#### socket.connect(path, [connectListener])
|
||||
### socket.connect(port, [host], [connectListener])
|
||||
### socket.connect(path, [connectListener])
|
||||
|
||||
Opens the connection for a given socket. If `port` and `host` are given,
|
||||
then the socket will be opened as a TCP socket, if `host` is omitted,
|
||||
@@ -266,7 +262,7 @@ The `connectListener` parameter will be added as an listener for the
|
||||
['connect'](#event_connect_) event.
|
||||
|
||||
|
||||
#### socket.bufferSize
|
||||
### socket.bufferSize
|
||||
|
||||
`net.Socket` has the property that `socket.write()` always works. This is to
|
||||
help users get up and running quickly. The computer cannot always keep up
|
||||
@@ -285,12 +281,12 @@ Users who experience large or growing `bufferSize` should attempt to
|
||||
"throttle" the data flows in their program with `pause()` and `resume()`.
|
||||
|
||||
|
||||
#### socket.setEncoding([encoding])
|
||||
### socket.setEncoding([encoding])
|
||||
|
||||
Sets the encoding (either `'ascii'`, `'utf8'`, or `'base64'`) for data that is
|
||||
received. Defaults to `null`.
|
||||
|
||||
#### socket.write(data, [encoding], [callback])
|
||||
### socket.write(data, [encoding], [callback])
|
||||
|
||||
Sends data on the socket. The second parameter specifies the encoding in the
|
||||
case of a string--it defaults to UTF8 encoding.
|
||||
@@ -302,7 +298,7 @@ buffer. Returns `false` if all or part of the data was queued in user memory.
|
||||
The optional `callback` parameter will be executed when the data is finally
|
||||
written out - this may not be immediately.
|
||||
|
||||
#### socket.end([data], [encoding])
|
||||
### socket.end([data], [encoding])
|
||||
|
||||
Half-closes the socket. i.e., it sends a FIN packet. It is possible the
|
||||
server will still send some data.
|
||||
@@ -310,21 +306,21 @@ server will still send some data.
|
||||
If `data` is specified, it is equivalent to calling
|
||||
`socket.write(data, encoding)` followed by `socket.end()`.
|
||||
|
||||
#### socket.destroy()
|
||||
### socket.destroy()
|
||||
|
||||
Ensures that no more I/O activity happens on this socket. Only necessary in
|
||||
case of errors (parse error or so).
|
||||
|
||||
#### socket.pause()
|
||||
### socket.pause()
|
||||
|
||||
Pauses the reading of data. That is, `'data'` events will not be emitted.
|
||||
Useful to throttle back an upload.
|
||||
|
||||
#### socket.resume()
|
||||
### socket.resume()
|
||||
|
||||
Resumes reading after a call to `pause()`.
|
||||
|
||||
#### socket.setTimeout(timeout, [callback])
|
||||
### socket.setTimeout(timeout, [callback])
|
||||
|
||||
Sets the socket to timeout after `timeout` milliseconds of inactivity on
|
||||
the socket. By default `net.Socket` do not have a timeout.
|
||||
@@ -338,14 +334,14 @@ If `timeout` is 0, then the existing idle timeout is disabled.
|
||||
The optional `callback` parameter will be added as a one time listener for the
|
||||
`'timeout'` event.
|
||||
|
||||
#### socket.setNoDelay([noDelay])
|
||||
### socket.setNoDelay([noDelay])
|
||||
|
||||
Disables the Nagle algorithm. By default TCP connections use the Nagle
|
||||
algorithm, they buffer data before sending it off. Setting `true` for
|
||||
`noDelay` will immediately fire off data each time `socket.write()` is called.
|
||||
`noDelay` defaults to `true`.
|
||||
|
||||
#### socket.setKeepAlive([enable], [initialDelay])
|
||||
### socket.setKeepAlive([enable], [initialDelay])
|
||||
|
||||
Enable/disable keep-alive functionality, and optionally set the initial
|
||||
delay before the first keepalive probe is sent on an idle socket.
|
||||
@@ -356,53 +352,53 @@ data packet received and the first keepalive probe. Setting 0 for
|
||||
initialDelay will leave the value unchanged from the default
|
||||
(or previous) setting. Defaults to `0`.
|
||||
|
||||
#### socket.address()
|
||||
### socket.address()
|
||||
|
||||
Returns the bound address and port of the socket as reported by the operating
|
||||
system. Returns an object with two properties, e.g.
|
||||
`{"address":"192.168.57.1", "port":62053}`
|
||||
|
||||
#### socket.remoteAddress
|
||||
### socket.remoteAddress
|
||||
|
||||
The string representation of the remote IP address. For example,
|
||||
`'74.125.127.100'` or `'2001:4860:a005::68'`.
|
||||
|
||||
#### socket.remotePort
|
||||
### socket.remotePort
|
||||
|
||||
The numeric representation of the remote port. For example,
|
||||
`80` or `21`.
|
||||
|
||||
#### socket.bytesRead
|
||||
### socket.bytesRead
|
||||
|
||||
The amount of received bytes.
|
||||
|
||||
#### socket.bytesWritten
|
||||
### socket.bytesWritten
|
||||
|
||||
The amount of bytes sent.
|
||||
|
||||
|
||||
`net.Socket` instances are EventEmitters with the following events:
|
||||
|
||||
#### Event: 'connect'
|
||||
### Event: 'connect'
|
||||
|
||||
`function () { }`
|
||||
|
||||
Emitted when a socket connection is successfully established.
|
||||
See `connect()`.
|
||||
|
||||
#### Event: 'data'
|
||||
### Event: 'data'
|
||||
|
||||
`function (data) { }`
|
||||
|
||||
Emitted when data is received. The argument `data` will be a `Buffer` or
|
||||
`String`. Encoding of data is set by `socket.setEncoding()`.
|
||||
(See the [Readable Stream](streams.html#readable_Stream) section for more
|
||||
(See the [Readable Stream](stream.html#readable_stream) section for more
|
||||
information.)
|
||||
|
||||
Note that the __data will be lost__ if there is no listener when a `Socket`
|
||||
emits a `'data'` event.
|
||||
|
||||
#### Event: 'end'
|
||||
### Event: 'end'
|
||||
|
||||
`function () { }`
|
||||
|
||||
@@ -415,7 +411,7 @@ its side allowing the user to write arbitrary amounts of data, with the
|
||||
caveat that the user is required to `end()` their side now.
|
||||
|
||||
|
||||
#### Event: 'timeout'
|
||||
### Event: 'timeout'
|
||||
|
||||
`function () { }`
|
||||
|
||||
@@ -425,7 +421,7 @@ the socket has been idle. The user must manually close the connection.
|
||||
See also: `socket.setTimeout()`
|
||||
|
||||
|
||||
#### Event: 'drain'
|
||||
### Event: 'drain'
|
||||
|
||||
`function () { }`
|
||||
|
||||
@@ -433,36 +429,33 @@ Emitted when the write buffer becomes empty. Can be used to throttle uploads.
|
||||
|
||||
See also: the return values of `socket.write()`
|
||||
|
||||
#### Event: 'error'
|
||||
### Event: 'error'
|
||||
|
||||
`function (exception) { }`
|
||||
|
||||
Emitted when an error occurs. The `'close'` event will be called directly
|
||||
following this event.
|
||||
|
||||
#### Event: 'close'
|
||||
### Event: 'close'
|
||||
|
||||
`function (had_error) { }`
|
||||
|
||||
Emitted once the socket is fully closed. The argument `had_error` is a boolean
|
||||
which says if the socket was closed due to a transmission error.
|
||||
|
||||
---
|
||||
|
||||
### net.isIP
|
||||
|
||||
#### net.isIP(input)
|
||||
## net.isIP
|
||||
## net.isIP(input)
|
||||
|
||||
Tests if input is an IP address. Returns 0 for invalid strings,
|
||||
returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.
|
||||
|
||||
|
||||
#### net.isIPv4(input)
|
||||
## net.isIPv4(input)
|
||||
|
||||
Returns true if input is a version 4 IP address, otherwise returns false.
|
||||
|
||||
|
||||
#### net.isIPv6(input)
|
||||
## net.isIPv6(input)
|
||||
|
||||
Returns true if input is a version 6 IP address, otherwise returns false.
|
||||
|
||||
+14
-12
@@ -1,44 +1,46 @@
|
||||
## os Module
|
||||
# os
|
||||
|
||||
Provides a few basic operating-system related utility functions.
|
||||
|
||||
Use `require('os')` to access this module.
|
||||
|
||||
### os.hostname()
|
||||
## os.hostname()
|
||||
|
||||
Returns the hostname of the operating system.
|
||||
|
||||
### os.type()
|
||||
## os.type()
|
||||
|
||||
Returns the operating system name.
|
||||
|
||||
### os.platform()
|
||||
## os.platform()
|
||||
|
||||
Returns the operating system platform.
|
||||
|
||||
### os.arch()
|
||||
## os.arch()
|
||||
|
||||
Returns the operating system CPU architecture.
|
||||
|
||||
### os.release()
|
||||
## os.release()
|
||||
|
||||
Returns the operating system release.
|
||||
|
||||
### os.uptime()
|
||||
## os.uptime()
|
||||
|
||||
Returns the system uptime in seconds.
|
||||
|
||||
### os.loadavg()
|
||||
## os.loadavg()
|
||||
|
||||
Returns an array containing the 1, 5, and 15 minute load averages.
|
||||
|
||||
### os.totalmem()
|
||||
## os.totalmem()
|
||||
|
||||
Returns the total amount of system memory in bytes.
|
||||
|
||||
### os.freemem()
|
||||
## os.freemem()
|
||||
|
||||
Returns the amount of free system memory in bytes.
|
||||
|
||||
### os.cpus()
|
||||
## os.cpus()
|
||||
|
||||
Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of CPU ticks spent in: user, nice, sys, idle, and irq).
|
||||
|
||||
@@ -109,7 +111,7 @@ Example inspection of os.cpus:
|
||||
idle: 1072572010,
|
||||
irq: 30 } } ]
|
||||
|
||||
### os.networkInterfaces()
|
||||
## os.networkInterfaces()
|
||||
|
||||
Get a list of network interfaces:
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
## Path
|
||||
# Path
|
||||
|
||||
This module contains utilities for handling and transforming file
|
||||
paths. Almost all these methods perform only string transformations.
|
||||
@@ -6,7 +6,7 @@ The file system is not consulted to check whether paths are valid.
|
||||
|
||||
Use `require('path')` to use this module. The following methods are provided:
|
||||
|
||||
### path.normalize(p)
|
||||
## path.normalize(p)
|
||||
|
||||
Normalize a string path, taking care of `'..'` and `'.'` parts.
|
||||
|
||||
@@ -20,7 +20,7 @@ Example:
|
||||
// returns
|
||||
'/foo/bar/baz/asdf'
|
||||
|
||||
### path.join([path1], [path2], [...])
|
||||
## path.join([path1], [path2], [...])
|
||||
|
||||
Join all arguments together and normalize the resulting path.
|
||||
Non-string arguments are ignored.
|
||||
@@ -35,7 +35,7 @@ Example:
|
||||
// returns
|
||||
'foo/bar'
|
||||
|
||||
### path.resolve([from ...], to)
|
||||
## path.resolve([from ...], to)
|
||||
|
||||
Resolves `to` to an absolute path.
|
||||
|
||||
@@ -74,7 +74,7 @@ Examples:
|
||||
// if currently in /home/myself/node, it returns
|
||||
'/home/myself/node/wwwroot/static_files/gif/image.gif'
|
||||
|
||||
### path.relative(from, to)
|
||||
## path.relative(from, to)
|
||||
|
||||
Solve the relative path from `from` to `to`.
|
||||
|
||||
@@ -94,7 +94,7 @@ Examples:
|
||||
// returns
|
||||
'../../impl/bbb'
|
||||
|
||||
### path.dirname(p)
|
||||
## path.dirname(p)
|
||||
|
||||
Return the directory name of a path. Similar to the Unix `dirname` command.
|
||||
|
||||
@@ -104,7 +104,7 @@ Example:
|
||||
// returns
|
||||
'/foo/bar/baz/asdf'
|
||||
|
||||
### path.basename(p, [ext])
|
||||
## path.basename(p, [ext])
|
||||
|
||||
Return the last portion of a path. Similar to the Unix `basename` command.
|
||||
|
||||
@@ -118,7 +118,7 @@ Example:
|
||||
// returns
|
||||
'quux'
|
||||
|
||||
### path.extname(p)
|
||||
## path.extname(p)
|
||||
|
||||
Return the extension of the path, from the last '.' to end of string
|
||||
in the last portion of the path. If there is no '.' in the last portion
|
||||
|
||||
+35
-30
@@ -1,10 +1,12 @@
|
||||
## process
|
||||
# process
|
||||
|
||||
<!-- type=global -->
|
||||
|
||||
The `process` object is a global object and can be accessed from anywhere.
|
||||
It is an instance of `EventEmitter`.
|
||||
|
||||
|
||||
### Event: 'exit'
|
||||
## Event: 'exit'
|
||||
|
||||
`function () {}`
|
||||
|
||||
@@ -22,7 +24,7 @@ Example of listening for `exit`:
|
||||
console.log('About to exit.');
|
||||
});
|
||||
|
||||
### Event: 'uncaughtException'
|
||||
## Event: 'uncaughtException'
|
||||
|
||||
`function (err) { }`
|
||||
|
||||
@@ -50,7 +52,10 @@ your program's flow. Especially for server programs that are designed to
|
||||
stay running forever, `uncaughtException` can be a useful safety mechanism.
|
||||
|
||||
|
||||
### Signal Events
|
||||
## Signal Events
|
||||
|
||||
<!--type=event-->
|
||||
<!--name=SIGINT, SIGUSR1, etc.-->
|
||||
|
||||
`function () {}`
|
||||
|
||||
@@ -70,7 +75,7 @@ An easy way to send the `SIGINT` signal is with `Control-C` in most terminal
|
||||
programs.
|
||||
|
||||
|
||||
### process.stdout
|
||||
## process.stdout
|
||||
|
||||
A `Writable Stream` to `stdout`.
|
||||
|
||||
@@ -86,7 +91,7 @@ that they refer to regular files or TTY file descriptors. In the case they
|
||||
refer to pipes, they are non-blocking like other streams.
|
||||
|
||||
|
||||
### process.stderr
|
||||
## process.stderr
|
||||
|
||||
A writable stream to stderr.
|
||||
|
||||
@@ -96,7 +101,7 @@ that they refer to regular files or TTY file descriptors. In the case they
|
||||
refer to pipes, they are non-blocking like other streams.
|
||||
|
||||
|
||||
### process.stdin
|
||||
## process.stdin
|
||||
|
||||
A `Readable Stream` for stdin. The stdin stream is paused by default, so one
|
||||
must call `process.stdin.resume()` to read from it.
|
||||
@@ -115,7 +120,7 @@ Example of opening standard input and listening for both events:
|
||||
});
|
||||
|
||||
|
||||
### process.argv
|
||||
## process.argv
|
||||
|
||||
An array containing the command line arguments. The first element will be
|
||||
'node', the second element will be the name of the JavaScript file. The
|
||||
@@ -136,7 +141,7 @@ This will generate:
|
||||
4: four
|
||||
|
||||
|
||||
### process.execPath
|
||||
## process.execPath
|
||||
|
||||
This is the absolute pathname of the executable that started the process.
|
||||
|
||||
@@ -145,12 +150,12 @@ Example:
|
||||
/usr/local/bin/node
|
||||
|
||||
|
||||
### process.abort()
|
||||
## process.abort()
|
||||
|
||||
This causes node to emit an abort. This will cause node to exit and
|
||||
generate a core file.
|
||||
|
||||
### process.chdir(directory)
|
||||
## process.chdir(directory)
|
||||
|
||||
Changes the current working directory of the process or throws an exception if that fails.
|
||||
|
||||
@@ -165,19 +170,19 @@ Changes the current working directory of the process or throws an exception if t
|
||||
|
||||
|
||||
|
||||
### process.cwd()
|
||||
## process.cwd()
|
||||
|
||||
Returns the current working directory of the process.
|
||||
|
||||
console.log('Current directory: ' + process.cwd());
|
||||
|
||||
|
||||
### process.env
|
||||
## process.env
|
||||
|
||||
An object containing the user environment. See environ(7).
|
||||
|
||||
|
||||
### process.exit([code])
|
||||
## process.exit([code])
|
||||
|
||||
Ends the process with the specified `code`. If omitted, exit uses the
|
||||
'success' code `0`.
|
||||
@@ -189,7 +194,7 @@ To exit with a 'failure' code:
|
||||
The shell that executed node should see the exit code as 1.
|
||||
|
||||
|
||||
### process.getgid()
|
||||
## process.getgid()
|
||||
|
||||
Gets the group identity of the process. (See getgid(2).)
|
||||
This is the numerical group id, not the group name.
|
||||
@@ -197,7 +202,7 @@ This is the numerical group id, not the group name.
|
||||
console.log('Current gid: ' + process.getgid());
|
||||
|
||||
|
||||
### process.setgid(id)
|
||||
## process.setgid(id)
|
||||
|
||||
Sets the group identity of the process. (See setgid(2).) This accepts either
|
||||
a numerical ID or a groupname string. If a groupname is specified, this method
|
||||
@@ -213,7 +218,7 @@ blocks while resolving it to a numerical ID.
|
||||
}
|
||||
|
||||
|
||||
### process.getuid()
|
||||
## process.getuid()
|
||||
|
||||
Gets the user identity of the process. (See getuid(2).)
|
||||
This is the numerical userid, not the username.
|
||||
@@ -221,7 +226,7 @@ This is the numerical userid, not the username.
|
||||
console.log('Current uid: ' + process.getuid());
|
||||
|
||||
|
||||
### process.setuid(id)
|
||||
## process.setuid(id)
|
||||
|
||||
Sets the user identity of the process. (See setuid(2).) This accepts either
|
||||
a numerical ID or a username string. If a username is specified, this method
|
||||
@@ -237,13 +242,13 @@ blocks while resolving it to a numerical ID.
|
||||
}
|
||||
|
||||
|
||||
### process.version
|
||||
## process.version
|
||||
|
||||
A compiled-in property that exposes `NODE_VERSION`.
|
||||
|
||||
console.log('Version: ' + process.version);
|
||||
|
||||
### process.versions
|
||||
## process.versions
|
||||
|
||||
A property exposing version strings of node and its dependencies.
|
||||
|
||||
@@ -258,14 +263,14 @@ Will output:
|
||||
openssl: '1.0.0e-fips' }
|
||||
|
||||
|
||||
### process.installPrefix
|
||||
## process.installPrefix
|
||||
|
||||
A compiled-in property that exposes `NODE_PREFIX`.
|
||||
|
||||
console.log('Prefix: ' + process.installPrefix);
|
||||
|
||||
|
||||
### process.kill(pid, [signal])
|
||||
## process.kill(pid, [signal])
|
||||
|
||||
Send a signal to a process. `pid` is the process id and `signal` is the
|
||||
string describing the signal to send. Signal names are strings like
|
||||
@@ -290,32 +295,32 @@ Example of sending a signal to yourself:
|
||||
process.kill(process.pid, 'SIGHUP');
|
||||
|
||||
|
||||
### process.pid
|
||||
## process.pid
|
||||
|
||||
The PID of the process.
|
||||
|
||||
console.log('This process is pid ' + process.pid);
|
||||
|
||||
### process.title
|
||||
## process.title
|
||||
|
||||
Getter/setter to set what is displayed in 'ps'.
|
||||
|
||||
|
||||
### process.arch
|
||||
## process.arch
|
||||
|
||||
What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`.
|
||||
|
||||
console.log('This processor architecture is ' + process.arch);
|
||||
|
||||
|
||||
### process.platform
|
||||
## process.platform
|
||||
|
||||
What platform you're running on. `'linux2'`, `'darwin'`, etc.
|
||||
|
||||
console.log('This platform is ' + process.platform);
|
||||
|
||||
|
||||
### process.memoryUsage()
|
||||
## process.memoryUsage()
|
||||
|
||||
Returns an object describing the memory usage of the Node process
|
||||
measured in bytes.
|
||||
@@ -333,7 +338,7 @@ This will generate:
|
||||
`heapTotal` and `heapUsed` refer to V8's memory usage.
|
||||
|
||||
|
||||
### process.nextTick(callback)
|
||||
## process.nextTick(callback)
|
||||
|
||||
On the next loop around the event loop call this callback.
|
||||
This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more
|
||||
@@ -344,7 +349,7 @@ efficient.
|
||||
});
|
||||
|
||||
|
||||
### process.umask([mask])
|
||||
## process.umask([mask])
|
||||
|
||||
Sets or reads the process's file mode creation mask. Child processes inherit
|
||||
the mask from the parent process. Returns the old mask if `mask` argument is
|
||||
@@ -357,6 +362,6 @@ given, otherwise returns the current mask.
|
||||
' to ' + newmask.toString(8));
|
||||
|
||||
|
||||
### process.uptime()
|
||||
## process.uptime()
|
||||
|
||||
Number of seconds Node has been running.
|
||||
@@ -1,9 +1,11 @@
|
||||
## Query String
|
||||
# Query String
|
||||
|
||||
<!--name=querystring-->
|
||||
|
||||
This module provides utilities for dealing with query strings.
|
||||
It provides the following methods:
|
||||
|
||||
### querystring.stringify(obj, [sep], [eq])
|
||||
## querystring.stringify(obj, [sep], [eq])
|
||||
|
||||
Serialize an object to a query string.
|
||||
Optionally override the default separator (`'&'`) and assignment (`'='`)
|
||||
@@ -19,7 +21,7 @@ Example:
|
||||
// returns
|
||||
'foo:bar;baz:qux'
|
||||
|
||||
### querystring.parse(str, [sep], [eq], [options])
|
||||
## querystring.parse(str, [sep], [eq], [options])
|
||||
|
||||
Deserialize a query string to an object.
|
||||
Optionally override the default separator (`'&'`) and assignment (`'='`)
|
||||
@@ -34,12 +36,12 @@ Example:
|
||||
// returns
|
||||
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
|
||||
|
||||
### querystring.escape
|
||||
## querystring.escape
|
||||
|
||||
The escape function used by `querystring.stringify`,
|
||||
provided so that it could be overridden if necessary.
|
||||
|
||||
### querystring.unescape
|
||||
## querystring.unescape
|
||||
|
||||
The unescape function used by `querystring.parse`,
|
||||
provided so that it could be overridden if necessary.
|
||||
@@ -1,4 +1,4 @@
|
||||
## Readline
|
||||
# Readline
|
||||
|
||||
To use this module, do `require('readline')`. Readline allows reading of a
|
||||
stream (such as STDIN) on a line-by-line basis.
|
||||
@@ -17,7 +17,7 @@ program to gracefully pause:
|
||||
i.pause();
|
||||
});
|
||||
|
||||
### rl.createInterface(input, output, completer)
|
||||
## rl.createInterface(input, output, completer)
|
||||
|
||||
Takes two streams and creates a readline interface. The `completer` function
|
||||
is used for autocompletion. When given a substring, it returns `[[substr1,
|
||||
@@ -35,6 +35,11 @@ Also `completer` can be run in async mode if it accepts two arguments:
|
||||
var readline = require('readline'),
|
||||
rl = readline.createInterface(process.stdin, process.stdout);
|
||||
|
||||
## Class: Interface
|
||||
|
||||
The class that represents a readline interface with a stdin and stdout
|
||||
stream.
|
||||
|
||||
### rl.setPrompt(prompt, length)
|
||||
|
||||
Sets the prompt, for example when you run `node` on the command line, you see
|
||||
@@ -48,8 +53,6 @@ options on a new line, giving the user a new spot to write.
|
||||
This will also resume the `in` stream used with `createInterface` if it has
|
||||
been paused.
|
||||
|
||||
<!-- ### rl.getColumns() Not available? -->
|
||||
|
||||
### rl.question(query, callback)
|
||||
|
||||
Prepends the prompt with `query` and invokes `callback` with the user's
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
## REPL
|
||||
# REPL
|
||||
|
||||
A Read-Eval-Print-Loop (REPL) is available both as a standalone program and easily
|
||||
includable in other programs. REPL provides a way to interactively run
|
||||
@@ -27,7 +27,7 @@ For example, you could add this to your bashrc file:
|
||||
alias node="env NODE_NO_READLINE=1 rlwrap node"
|
||||
|
||||
|
||||
### repl.start([prompt], [stream], [eval], [useGlobal], [ignoreUndefined])
|
||||
## repl.start([prompt], [stream], [eval], [useGlobal], [ignoreUndefined])
|
||||
|
||||
Starts a REPL with `prompt` as the prompt and `stream` for all I/O. `prompt`
|
||||
is optional and defaults to `> `. `stream` is optional and defaults to
|
||||
@@ -77,7 +77,9 @@ By starting a REPL from a Unix socket-based server instead of stdin, you can
|
||||
connect to a long-running node process without restarting it.
|
||||
|
||||
|
||||
### REPL Features
|
||||
## REPL Features
|
||||
|
||||
<!-- type=misc -->
|
||||
|
||||
Inside the REPL, Control+D will exit. Multi-line expressions can be input.
|
||||
Tab completion is supported for both global and local variables.
|
||||
|
||||
+14
-10
@@ -1,10 +1,14 @@
|
||||
## console
|
||||
# console
|
||||
|
||||
* {Object}
|
||||
|
||||
<!--type=global-->
|
||||
|
||||
For printing to stdout and stderr. Similar to the console object functions
|
||||
provided by most web browsers, here the output is sent to stdout or stderr.
|
||||
|
||||
|
||||
### console.log()
|
||||
## console.log()
|
||||
|
||||
Prints to stdout with newline. This function can take multiple arguments in a
|
||||
`printf()`-like way. Example:
|
||||
@@ -15,25 +19,25 @@ If formatting elements are not found in the first string then `util.inspect`
|
||||
is used on each argument.
|
||||
See [util.format()](util.html#util.format) for more information.
|
||||
|
||||
### console.info()
|
||||
## console.info()
|
||||
|
||||
Same as `console.log`.
|
||||
|
||||
### console.warn()
|
||||
### console.error()
|
||||
## console.warn()
|
||||
## console.error()
|
||||
|
||||
Same as `console.log` but prints to stderr.
|
||||
|
||||
### console.dir(obj)
|
||||
## console.dir(obj)
|
||||
|
||||
Uses `util.inspect` on `obj` and prints resulting string to stderr.
|
||||
|
||||
### console.time(label)
|
||||
## console.time(label)
|
||||
|
||||
Mark a time.
|
||||
|
||||
|
||||
### console.timeEnd(label)
|
||||
## console.timeEnd(label)
|
||||
|
||||
Finish timer, record output. Example
|
||||
|
||||
@@ -44,11 +48,11 @@ Finish timer, record output. Example
|
||||
console.timeEnd('100-elements');
|
||||
|
||||
|
||||
### console.trace()
|
||||
## console.trace()
|
||||
|
||||
Print a stack trace to stderr of the current position.
|
||||
|
||||
### console.assert()
|
||||
## console.assert()
|
||||
|
||||
Same as `assert.ok()`.
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
## Streams
|
||||
# Stream
|
||||
|
||||
A stream is an abstract interface implemented by various objects in Node.
|
||||
For example a request to an HTTP server is a stream, as is stdout. Streams
|
||||
are readable, writable, or both. All streams are instances of `EventEmitter`.
|
||||
|
||||
You can load up the Stream base class by doing `require('stream')`.
|
||||
|
||||
## Readable Stream
|
||||
|
||||
<!--type=class-->
|
||||
|
||||
A `Readable Stream` has the following methods, members, and events.
|
||||
|
||||
### Event: 'data'
|
||||
@@ -99,6 +103,8 @@ This keeps `process.stdout` open so that "Goodbye" can be written at the end.
|
||||
|
||||
## Writable Stream
|
||||
|
||||
<!--type=class-->
|
||||
|
||||
A `Writable Stream` has the following methods, members, and events.
|
||||
|
||||
### Event: 'drain'
|
||||
@@ -1,4 +1,6 @@
|
||||
## Synopsis
|
||||
# Synopsis
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
An example of a [web server](http.html) written with Node which responds with 'Hello
|
||||
World':
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
## Timers
|
||||
# Timers
|
||||
|
||||
### setTimeout(callback, delay, [arg], [...])
|
||||
All of the timer functions are globals. You do not need to `require()`
|
||||
this module in order to use them.
|
||||
|
||||
## setTimeout(callback, delay, [arg], [...])
|
||||
|
||||
To schedule execution of a one-time `callback` after `delay` milliseconds. Returns a
|
||||
`timeoutId` for possible use with `clearTimeout()`. Optionally you can
|
||||
@@ -11,16 +14,16 @@ It is important to note that your callback will probably not be called in exactl
|
||||
the callback will fire, nor of the ordering things will fire in. The callback will
|
||||
be called as close as possible to the time specified.
|
||||
|
||||
### clearTimeout(timeoutId)
|
||||
## clearTimeout(timeoutId)
|
||||
|
||||
Prevents a timeout from triggering.
|
||||
|
||||
### setInterval(callback, delay, [arg], [...])
|
||||
## setInterval(callback, delay, [arg], [...])
|
||||
|
||||
To schedule the repeated execution of `callback` every `delay` milliseconds.
|
||||
Returns a `intervalId` for possible use with `clearInterval()`. Optionally
|
||||
you can also pass arguments to the callback.
|
||||
|
||||
### clearInterval(intervalId)
|
||||
## clearInterval(intervalId)
|
||||
|
||||
Stops a interval from triggering.
|
||||
+18
-10
@@ -1,4 +1,4 @@
|
||||
## TLS (SSL)
|
||||
# TLS (SSL)
|
||||
|
||||
Use `require('tls')` to access this module.
|
||||
|
||||
@@ -26,7 +26,9 @@ Alternatively you can send the CSR to a Certificate Authority for signing.
|
||||
(TODO: docs on creating a CA, for now interested users should just look at
|
||||
`test/fixtures/keys/Makefile` in the Node source code)
|
||||
|
||||
### Client-initiated renegotiation attack mitigation
|
||||
## Client-initiated renegotiation attack mitigation
|
||||
|
||||
<!-- type=misc -->
|
||||
|
||||
The TLS protocol lets the client renegotiate certain aspects of the TLS session.
|
||||
Unfortunately, session renegotiation requires a disproportional amount of
|
||||
@@ -49,7 +51,9 @@ and tap `R<CR>` (that's the letter `R` followed by a carriage return) a few
|
||||
times.
|
||||
|
||||
|
||||
### NPN and SNI
|
||||
## NPN and SNI
|
||||
|
||||
<!-- type=misc -->
|
||||
|
||||
NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS
|
||||
handshake extensions allowing you:
|
||||
@@ -138,8 +142,8 @@ You can test this server by connecting to it with `openssl s_client`:
|
||||
openssl s_client -connect 127.0.0.1:8000
|
||||
|
||||
|
||||
#### tls.connect(options, [secureConnectListener])
|
||||
#### tls.connect(port, [host], [options], [secureConnectListener])
|
||||
## tls.connect(options, [secureConnectListener])
|
||||
## tls.connect(port, [host], [options], [secureConnectListener])
|
||||
|
||||
Creates a new client connection to the given `port` and `host` (old API) or
|
||||
`options.port` and `options.host`. (If `host` is omitted, it defaults to
|
||||
@@ -232,6 +236,10 @@ and the cleartext one is used as a replacement for the initial encrypted stream.
|
||||
`tls.createSecurePair()` returns a SecurePair object with
|
||||
[cleartext](#tls.CleartextStream) and `encrypted` stream properties.
|
||||
|
||||
## Class: SecurePair
|
||||
|
||||
Returned by tls.createSecurePair.
|
||||
|
||||
### Event: 'secure'
|
||||
|
||||
The event is emitted from the SecurePair once the pair has successfully
|
||||
@@ -241,7 +249,7 @@ Similarly to the checking for the server 'secureConnection' event,
|
||||
pair.cleartext.authorized should be checked to confirm whether the certificate
|
||||
used properly authorized.
|
||||
|
||||
## tls.Server
|
||||
## Class: tls.Server
|
||||
|
||||
This class is a subclass of `net.Server` and has the same methods on it.
|
||||
Instead of accepting just raw TCP connections, this accepts encrypted
|
||||
@@ -315,17 +323,17 @@ gets high.
|
||||
The number of concurrent connections on the server.
|
||||
|
||||
|
||||
## tls.CleartextStream
|
||||
## Class: tls.CleartextStream
|
||||
|
||||
This is a stream on top of the *Encrypted* stream that makes it possible to
|
||||
read/write an encrypted data as a cleartext data.
|
||||
|
||||
This instance implements a duplex [Stream](streams.html#streams) interfaces.
|
||||
This instance implements a duplex [Stream](stream.html) interfaces.
|
||||
It has all the common stream methods and events.
|
||||
|
||||
### Event: 'secureConnect'
|
||||
A ClearTextStream is the `clear` member of a SecurePair object.
|
||||
|
||||
`function () {}`
|
||||
### Event: 'secureConnect'
|
||||
|
||||
This event is emitted after a new connection has been successfully handshaked.
|
||||
The listener will be called no matter if the server's certificate was
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
## TTY
|
||||
# TTY
|
||||
|
||||
Use `require('tty')` to access this module.
|
||||
|
||||
@@ -16,23 +16,23 @@ Example:
|
||||
|
||||
|
||||
|
||||
### tty.isatty(fd)
|
||||
## tty.isatty(fd)
|
||||
|
||||
Returns `true` or `false` depending on if the `fd` is associated with a
|
||||
terminal.
|
||||
|
||||
|
||||
### tty.setRawMode(mode)
|
||||
## tty.setRawMode(mode)
|
||||
|
||||
`mode` should be `true` or `false`. This sets the properties of the current
|
||||
process's stdin fd to act either as a raw device or default.
|
||||
|
||||
|
||||
### tty.setWindowSize(fd, row, col)
|
||||
## tty.setWindowSize(fd, row, col)
|
||||
|
||||
This function was removed in v0.6.0.
|
||||
|
||||
### tty.getWindowSize(fd)
|
||||
## tty.getWindowSize(fd)
|
||||
|
||||
This function was removed in v0.6.0. Use `process.stdout.getWindowSize()`
|
||||
instead.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
## URL
|
||||
# URL
|
||||
|
||||
This module has utilities for URL resolution and parsing.
|
||||
Call `require('url')` to use it.
|
||||
@@ -45,7 +45,7 @@ string will not be in the parsed object. Examples are shown for the URL
|
||||
|
||||
The following methods are provided by the URL module:
|
||||
|
||||
### url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
|
||||
## url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
|
||||
|
||||
Take a URL string, and return an object.
|
||||
|
||||
@@ -57,7 +57,7 @@ Pass `true` as the third argument to treat `//foo/bar` as
|
||||
`{ host: 'foo', pathname: '/bar' }` rather than
|
||||
`{ pathname: '//foo/bar' }`. Defaults to `false`.
|
||||
|
||||
### url.format(urlObj)
|
||||
## url.format(urlObj)
|
||||
|
||||
Take a parsed URL object, and return a formatted URL string.
|
||||
|
||||
@@ -75,6 +75,6 @@ Take a parsed URL object, and return a formatted URL string.
|
||||
* `search` is treated the same with or without the leading `?` (question mark)
|
||||
* `hash` is treated the same with or without the leading `#` (pound sign, anchor)
|
||||
|
||||
### url.resolve(from, to)
|
||||
## url.resolve(from, to)
|
||||
|
||||
Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.
|
||||
+11
-11
@@ -1,10 +1,10 @@
|
||||
## util
|
||||
# util
|
||||
|
||||
These functions are in the module `'util'`. Use `require('util')` to access
|
||||
them.
|
||||
|
||||
|
||||
### util.format()
|
||||
## util.format()
|
||||
|
||||
Returns a formatted string using the first argument as a `printf`-like format.
|
||||
|
||||
@@ -35,7 +35,7 @@ Each argument is converted to a string with `util.inspect()`.
|
||||
util.format(1, 2, 3); // '1 2 3'
|
||||
|
||||
|
||||
### util.debug(string)
|
||||
## util.debug(string)
|
||||
|
||||
A synchronous output function. Will block the process and
|
||||
output `string` immediately to `stderr`.
|
||||
@@ -43,14 +43,14 @@ output `string` immediately to `stderr`.
|
||||
require('util').debug('message on stderr');
|
||||
|
||||
|
||||
### util.log(string)
|
||||
## util.log(string)
|
||||
|
||||
Output with timestamp on `stdout`.
|
||||
|
||||
require('util').log('Timestamped message.');
|
||||
|
||||
|
||||
### util.inspect(object, [showHidden], [depth], [colors])
|
||||
## util.inspect(object, [showHidden], [depth], [colors])
|
||||
|
||||
Return a string representation of `object`, which is useful for debugging.
|
||||
|
||||
@@ -73,7 +73,7 @@ Example of inspecting all properties of the `util` object:
|
||||
console.log(util.inspect(util, true, null));
|
||||
|
||||
|
||||
### util.isArray(object)
|
||||
## util.isArray(object)
|
||||
|
||||
Returns `true` if the given "object" is an `Array`. `false` otherwise.
|
||||
|
||||
@@ -87,7 +87,7 @@ Returns `true` if the given "object" is an `Array`. `false` otherwise.
|
||||
// false
|
||||
|
||||
|
||||
### util.isRegExp(object)
|
||||
## util.isRegExp(object)
|
||||
|
||||
Returns `true` if the given "object" is a `RegExp`. `false` otherwise.
|
||||
|
||||
@@ -101,7 +101,7 @@ Returns `true` if the given "object" is a `RegExp`. `false` otherwise.
|
||||
// false
|
||||
|
||||
|
||||
### util.isDate(object)
|
||||
## util.isDate(object)
|
||||
|
||||
Returns `true` if the given "object" is a `Date`. `false` otherwise.
|
||||
|
||||
@@ -115,7 +115,7 @@ Returns `true` if the given "object" is a `Date`. `false` otherwise.
|
||||
// false
|
||||
|
||||
|
||||
### util.isError(object)
|
||||
## util.isError(object)
|
||||
|
||||
Returns `true` if the given "object" is an `Error`. `false` otherwise.
|
||||
|
||||
@@ -129,7 +129,7 @@ Returns `true` if the given "object" is an `Error`. `false` otherwise.
|
||||
// false
|
||||
|
||||
|
||||
### util.pump(readableStream, writableStream, [callback])
|
||||
## util.pump(readableStream, writableStream, [callback])
|
||||
|
||||
Experimental
|
||||
|
||||
@@ -140,7 +140,7 @@ an error as its only argument and is called when `writableStream` is closed or
|
||||
when an error occurs.
|
||||
|
||||
|
||||
### util.inherits(constructor, superConstructor)
|
||||
## util.inherits(constructor, superConstructor)
|
||||
|
||||
Inherit the prototype methods from one
|
||||
[constructor](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor)
|
||||
|
||||
+12
-6
@@ -1,4 +1,6 @@
|
||||
## Executing JavaScript
|
||||
# Executing JavaScript
|
||||
|
||||
<!--name=vm-->
|
||||
|
||||
You can access this module with:
|
||||
|
||||
@@ -7,7 +9,7 @@ You can access this module with:
|
||||
JavaScript code can be compiled and run immediately or compiled, saved, and run later.
|
||||
|
||||
|
||||
### vm.runInThisContext(code, [filename])
|
||||
## vm.runInThisContext(code, [filename])
|
||||
|
||||
`vm.runInThisContext()` compiles `code`, runs it and returns the result. Running
|
||||
code does not have access to local scope. `filename` is optional, it's used only
|
||||
@@ -37,7 +39,7 @@ In case of syntax error in `code`, `vm.runInThisContext` emits the syntax error
|
||||
and throws an exception.
|
||||
|
||||
|
||||
### vm.runInNewContext(code, [sandbox], [filename])
|
||||
## vm.runInNewContext(code, [sandbox], [filename])
|
||||
|
||||
`vm.runInNewContext` compiles `code`, then runs it in `sandbox` and returns the
|
||||
result. Running code does not have access to local scope. The object `sandbox`
|
||||
@@ -66,7 +68,7 @@ requires a separate process.
|
||||
In case of syntax error in `code`, `vm.runInNewContext` emits the syntax error to stderr
|
||||
and throws an exception.
|
||||
|
||||
### vm.runInContext(code, context, [filename])
|
||||
## vm.runInContext(code, context, [filename])
|
||||
|
||||
`vm.runInContext` compiles `code`, then runs it in `context` and returns the
|
||||
result. A (V8) context comprises a global object, together with a set of
|
||||
@@ -100,14 +102,14 @@ requires a separate process.
|
||||
In case of syntax error in `code`, `vm.runInContext` emits the syntax error to stderr
|
||||
and throws an exception.
|
||||
|
||||
### vm.createContext([initSandbox])
|
||||
## vm.createContext([initSandbox])
|
||||
|
||||
`vm.createContext` creates a new context which is suitable for use as the 2nd argument of a subsequent
|
||||
call to `vm.runInContext`. A (V8) context comprises a global object together with a set of
|
||||
build-in objects and functions. The optional argument `initSandbox` will be shallow-copied
|
||||
to seed the initial contents of the global object used by the context.
|
||||
|
||||
### vm.createScript(code, [filename])
|
||||
## vm.createScript(code, [filename])
|
||||
|
||||
`createScript` compiles `code` but does not run it. Instead, it returns a
|
||||
`vm.Script` object representing this compiled code. This script can be run
|
||||
@@ -119,6 +121,10 @@ In case of syntax error in `code`, `createScript` prints the syntax error to std
|
||||
and throws an exception.
|
||||
|
||||
|
||||
## Class: Script
|
||||
|
||||
A class for running scripts. Returned by vm.createScript.
|
||||
|
||||
### script.runInThisContext()
|
||||
|
||||
Similar to `vm.runInThisContext` but a method of a precompiled `Script` object.
|
||||
|
||||
+33
-25
@@ -1,4 +1,4 @@
|
||||
## Zlib
|
||||
# Zlib
|
||||
|
||||
You can access this module with:
|
||||
|
||||
@@ -8,7 +8,7 @@ This provides bindings to Gzip/Gunzip, Deflate/Inflate, and
|
||||
DeflateRaw/InflateRaw classes. Each class takes the same options, and
|
||||
is a readable/writable Stream.
|
||||
|
||||
### Examples
|
||||
## Examples
|
||||
|
||||
Compressing or decompressing a file can be done by piping an
|
||||
fs.ReadStream into a zlib stream, then into an fs.WriteStream.
|
||||
@@ -101,109 +101,115 @@ tradeoffs involved in zlib usage.
|
||||
}
|
||||
}).listen(1337);
|
||||
|
||||
### Constants
|
||||
## Constants
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
All of the constants defined in zlib.h are also defined on
|
||||
`require('zlib')`. They are described in more detail in the zlib
|
||||
documentation. See <http://zlib.net/manual.html#Constants>
|
||||
for more details.
|
||||
|
||||
### zlib.createGzip([options])
|
||||
## zlib.createGzip([options])
|
||||
|
||||
Returns a new [Gzip](#zlib.Gzip) object with an [options](#options).
|
||||
|
||||
### zlib.createGunzip([options])
|
||||
## zlib.createGunzip([options])
|
||||
|
||||
Returns a new [Gunzip](#zlib.Gunzip) object with an [options](#options).
|
||||
|
||||
### zlib.createDeflate([options])
|
||||
## zlib.createDeflate([options])
|
||||
|
||||
Returns a new [Deflate](#zlib.Deflate) object with an [options](#options).
|
||||
|
||||
### zlib.createInflate([options])
|
||||
## zlib.createInflate([options])
|
||||
|
||||
Returns a new [Inflate](#zlib.Inflate) object with an [options](#options).
|
||||
|
||||
### zlib.createDeflateRaw([options])
|
||||
## zlib.createDeflateRaw([options])
|
||||
|
||||
Returns a new [DeflateRaw](#zlib.DeflateRaw) object with an [options](#options).
|
||||
|
||||
### zlib.createInflateRaw([options])
|
||||
## zlib.createInflateRaw([options])
|
||||
|
||||
Returns a new [InflateRaw](#zlib.InflateRaw) object with an [options](#options).
|
||||
|
||||
### zlib.createUnzip([options])
|
||||
## zlib.createUnzip([options])
|
||||
|
||||
Returns a new [Unzip](#zlib.Unzip) object with an [options](#options).
|
||||
|
||||
|
||||
### zlib.Gzip
|
||||
## Class: zlib.Gzip
|
||||
|
||||
Compress data using gzip.
|
||||
|
||||
### zlib.Gunzip
|
||||
## Class: zlib.Gunzip
|
||||
|
||||
Decompress a gzip stream.
|
||||
|
||||
### zlib.Deflate
|
||||
## Class: zlib.Deflate
|
||||
|
||||
Compress data using deflate.
|
||||
|
||||
### zlib.Inflate
|
||||
## Class: zlib.Inflate
|
||||
|
||||
Decompress a deflate stream.
|
||||
|
||||
### zlib.DeflateRaw
|
||||
## Class: zlib.DeflateRaw
|
||||
|
||||
Compress data using deflate, and do not append a zlib header.
|
||||
|
||||
### zlib.InflateRaw
|
||||
## Class: zlib.InflateRaw
|
||||
|
||||
Decompress a raw deflate stream.
|
||||
|
||||
### zlib.Unzip
|
||||
## Class: zlib.Unzip
|
||||
|
||||
Decompress either a Gzip- or Deflate-compressed stream by auto-detecting
|
||||
the header.
|
||||
|
||||
## Convenience Methods
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
All of these take a string or buffer as the first argument, and call the
|
||||
supplied callback with `callback(error, result)`. The
|
||||
compression/decompression engine is created using the default settings
|
||||
in all convenience methods. To supply different options, use the
|
||||
zlib classes directly.
|
||||
|
||||
### zlib.deflate(buf, callback)
|
||||
## zlib.deflate(buf, callback)
|
||||
|
||||
Compress a string with Deflate.
|
||||
|
||||
### zlib.deflateRaw(buf, callback)
|
||||
## zlib.deflateRaw(buf, callback)
|
||||
|
||||
Compress a string with DeflateRaw.
|
||||
|
||||
### zlib.gzip(buf, callback)
|
||||
## zlib.gzip(buf, callback)
|
||||
|
||||
Compress a string with Gzip.
|
||||
|
||||
### zlib.gunzip(buf, callback)
|
||||
## zlib.gunzip(buf, callback)
|
||||
|
||||
Decompress a raw Buffer with Gunzip.
|
||||
|
||||
### zlib.inflate(buf, callback)
|
||||
## zlib.inflate(buf, callback)
|
||||
|
||||
Decompress a raw Buffer with Inflate.
|
||||
|
||||
### zlib.inflateRaw(buf, callback)
|
||||
## zlib.inflateRaw(buf, callback)
|
||||
|
||||
Decompress a raw Buffer with InflateRaw.
|
||||
|
||||
### zlib.unzip(buf, callback)
|
||||
## zlib.unzip(buf, callback)
|
||||
|
||||
Decompress a raw Buffer with Unzip.
|
||||
|
||||
## Options
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
Each class takes an options object. All options are optional. (The
|
||||
convenience methods use the default settings for all options.)
|
||||
|
||||
@@ -220,7 +226,9 @@ relevant when compressing, and are ignored by the decompression classes.
|
||||
See the description of `deflateInit2` and `inflateInit2` at
|
||||
<http://zlib.net/manual.html#Advanced> for more information on these.
|
||||
|
||||
### Memory Usage Tuning
|
||||
## Memory Usage Tuning
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
From `zlib/zconf.h`, modified to node's usage:
|
||||
|
||||
|
||||
+30
-29
@@ -12,7 +12,7 @@ body {
|
||||
border-top: 6px #8CC84B solid;
|
||||
}
|
||||
a {
|
||||
color: #690;
|
||||
color: #480;
|
||||
text-decoration: underline;
|
||||
}
|
||||
a:visited {
|
||||
@@ -123,61 +123,61 @@ h1, h2, h3, h4, h5, h6 {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
h1 {
|
||||
header h1 {
|
||||
font-family: Georgia, FreeSerif, Times, serif;
|
||||
font-size: 30px;
|
||||
font-weight: normal;
|
||||
line-height: 36px;
|
||||
color: #690;
|
||||
color: #480;
|
||||
margin: 15px 0 11px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
h1 {
|
||||
font-size: 29px;
|
||||
line-height: 33px;
|
||||
margin: 2em 0 15px;
|
||||
}
|
||||
|
||||
#toc + h2 {
|
||||
#toc + h1 {
|
||||
margin-top:1em;
|
||||
padding-top:0;
|
||||
}
|
||||
|
||||
h3 {
|
||||
h2 {
|
||||
font-size: 1.4em;
|
||||
line-height: 1.0909em;
|
||||
margin: 1.5em 0 0.5em;
|
||||
}
|
||||
|
||||
h2 + h2 {
|
||||
margin: 0 0 0.5em;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1.3em;
|
||||
line-height: 1.1282em;
|
||||
margin: 2.2em 0 0.5em;
|
||||
}
|
||||
|
||||
h3 + h3 {
|
||||
margin: 0 0 0.5em;
|
||||
}
|
||||
|
||||
h4 {
|
||||
font-size: 1.3em;
|
||||
line-height: 1.1282em;
|
||||
margin: 2.2em 0 0.5em;
|
||||
}
|
||||
|
||||
h4 + h4 {
|
||||
margin: 0 0 0.5em;
|
||||
}
|
||||
|
||||
h3, h4 {
|
||||
h2, h3 {
|
||||
position:relative;
|
||||
padding-right:40px;
|
||||
}
|
||||
h2 span, h3 span, h4 span {
|
||||
h1 span, h2 span, h3 span {
|
||||
position:absolute;
|
||||
display:block;
|
||||
top:0;
|
||||
right:0;
|
||||
opacity: 0.3;
|
||||
}
|
||||
h2 span:hover, h3 span:hover, h4 span:hover {
|
||||
h1 span:hover, h2 span:hover, h3 span:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
h2 span a, h3 span a, h4 span a {
|
||||
h1 span a, h2 span a, h3 span a {
|
||||
font-size: 0.8em;
|
||||
color: #000;
|
||||
text-decoration: none;
|
||||
@@ -185,7 +185,7 @@ h4 + h4 {
|
||||
font-weight:bold;
|
||||
}
|
||||
|
||||
h2 span a.top, h3 span a.top, h4 span a.top {
|
||||
h1 span a.top, h3 span a.top, h3 span a.top {
|
||||
/* XXX Get an image and clean up these two links
|
||||
* so that they look nice next to one another.
|
||||
* http://www.chrisglass.com/work/nodejs/website/v05/docs.html
|
||||
@@ -210,7 +210,7 @@ h6 {
|
||||
font-family: Monaco, Consolas, "Lucida Console", monospace;
|
||||
margin: 0; padding: 0;
|
||||
}
|
||||
|
||||
|
||||
.pre {
|
||||
font-family: Monaco, Consolas, "Lucida Console", monospace;
|
||||
line-height: 1.5438em;
|
||||
@@ -226,7 +226,7 @@ h6 {
|
||||
margin: -0.5em 0 1.1em;
|
||||
overflow-x:auto;
|
||||
}
|
||||
|
||||
|
||||
pre + h3 {
|
||||
margin-top: 2.225em;
|
||||
}
|
||||
@@ -271,22 +271,23 @@ hr {
|
||||
line-height: 21px;
|
||||
margin: 0 0 0.5em;
|
||||
}
|
||||
|
||||
|
||||
#toc h2 a {
|
||||
float: right;
|
||||
}
|
||||
|
||||
|
||||
#toc hr {
|
||||
margin: 1em 0 2em;
|
||||
}
|
||||
|
||||
#toc ul {
|
||||
#toc ul, #api-section-index ul li, #api-section-index ul {
|
||||
font-family: Georgia, FreeSerif, Times, serif;
|
||||
color:#666!important;
|
||||
}
|
||||
|
||||
#toc ul a {
|
||||
text-decoration:none;
|
||||
border-bottom:1px dotted #690;
|
||||
border-bottom:1px dotted #480;
|
||||
}
|
||||
#toc ul a:hover, #toc ul a:focus {
|
||||
border-bottom:1px dotted #fff;
|
||||
@@ -430,14 +431,14 @@ a.anchor {
|
||||
#footer a {
|
||||
text-decoration:none;
|
||||
border:none;
|
||||
color: #690;
|
||||
color: #480;
|
||||
}
|
||||
#footer a:hover {
|
||||
color:#000;
|
||||
}
|
||||
|
||||
#footer p a {
|
||||
border-bottom:1px dotted #690;
|
||||
border-bottom:1px dotted #480;
|
||||
color: #878b78;
|
||||
}
|
||||
|
||||
|
||||
+20
-14
@@ -2,12 +2,12 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>{{section}}Node.js v0.7.5 Manual & Documentation</title>
|
||||
<title>__SECTION__ Node.js __VERSION__ Manual & Documentation</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
<link rel="stylesheet" href="assets/sh.css">
|
||||
<link rel="canonical" href="http://nodejs.org/docs/latest/api/{{filename}}.html">
|
||||
<link rel="canonical" href="http://nodejs.org/api/__FILENAME__.html">
|
||||
</head>
|
||||
<body class="alt apidoc">
|
||||
<body class="alt apidoc" id="api-section-__FILENAME__">
|
||||
<div id="intro" class="interior">
|
||||
<a href="/" title="Go back to the home page">
|
||||
<img id="logo" src="http://nodejs.org/images/logo-light.png" alt="node.js">
|
||||
@@ -30,16 +30,22 @@
|
||||
</div>
|
||||
|
||||
<div id="column1" class="interior">
|
||||
<header>
|
||||
<h1>Node.js v0.7.5 Manual & Documentation</h1>
|
||||
<div id="gtoc">
|
||||
<p><a href="index.html" name="toc">Index</a> | <a href="all.html">View on single page</a></p>
|
||||
<header>
|
||||
<h1>Node.js __VERSION__ Manual & Documentation</h1>
|
||||
<div id="gtoc">
|
||||
<p><a href="index.html" name="toc">Index</a> | <a href="all.html">View on single page</a></p>
|
||||
</div>
|
||||
<hr>
|
||||
</header>
|
||||
|
||||
<div id="toc">
|
||||
<h2>Table of Contents</h2>
|
||||
__TOC__
|
||||
</div>
|
||||
|
||||
<div id="apicontent">
|
||||
__CONTENT__
|
||||
</div>
|
||||
<hr>
|
||||
</header>
|
||||
<div id="apicontent">
|
||||
{{content}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="footer">
|
||||
@@ -56,9 +62,9 @@
|
||||
<li><a href="http://twitter.com/nodejs" class="twitter">@nodejs</a></li>
|
||||
</ul>
|
||||
|
||||
<p>Copyright 2012 <a href="http://joyent.com">Joyent, Inc</a>, Node.js is a <a href="/trademark-policy.pdf">trademark</a> of Joyent, Inc. View <a href="https://raw.github.com/joyent/node/v0.7.5/LICENSE">license</a>.</p>
|
||||
<p>Copyright 2010 <a href="http://joyent.com">Joyent, Inc</a>, Node.js is a <a href="/trademark-policy.pdf">trademark</a> of Joyent, Inc. View <a href="https://raw.github.com/joyent/node/__VERSION__/LICENSE">license</a>.</p>
|
||||
</div>
|
||||
|
||||
|
||||
<script src="assets/sh_main.js"></script>
|
||||
<script src="assets/sh_javascript.min.js"></script>
|
||||
<script>highlight(undefined, undefined, 'pre');</script>
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
Here's how the node docs work.
|
||||
|
||||
1:1 relationship from `lib/<module>.js` to `doc/api/<module>.markdown`
|
||||
|
||||
Each type of heading has a description block.
|
||||
|
||||
|
||||
## module
|
||||
|
||||
Stability: 3 - Stable
|
||||
|
||||
description and examples.
|
||||
|
||||
### module.property
|
||||
|
||||
* Type
|
||||
|
||||
description of the property.
|
||||
|
||||
### module.someFunction(x, y, [z=100])
|
||||
|
||||
* `x` {String} the description of the string
|
||||
* `y` {Boolean} Should I stay or should I go?
|
||||
* `z` {Number} How many zebras to bring.
|
||||
|
||||
A description of the function.
|
||||
|
||||
### Event: 'blerg'
|
||||
|
||||
* Argument: SomeClass object.
|
||||
|
||||
Modules don't usually raise events on themselves. `cluster` is the
|
||||
only exception.
|
||||
|
||||
## Class: SomeClass
|
||||
|
||||
description of the class.
|
||||
|
||||
### Class Method: SomeClass.classMethod(anArg)
|
||||
|
||||
* `anArg` {Object} Just an argument
|
||||
* `field` {String} anArg can have this field.
|
||||
* `field2` {Boolean} Another field. Default: `false`.
|
||||
* Return: {Boolean} `true` if it worked.
|
||||
|
||||
Description of the method for humans.
|
||||
|
||||
### someClass.nextSibling()
|
||||
|
||||
* Return: {SomeClass object | null} The next someClass in line.
|
||||
|
||||
### someClass.someProperty
|
||||
|
||||
* String
|
||||
|
||||
The indication of what someProperty is.
|
||||
|
||||
### Event: 'grelb'
|
||||
|
||||
* `isBlerg` {Boolean}
|
||||
|
||||
This event is emitted on instances of SomeClass, not on the module itself.
|
||||
|
||||
|
||||
* Modules have (description, Properties, Functions, Classes, Examples)
|
||||
* Properties have (type, description)
|
||||
* Functions have (list of arguments, description)
|
||||
* Classes have (description, Properties, Methods, Events)
|
||||
* Events have (list of arguments, description)
|
||||
* Methods have (list of arguments, description)
|
||||
* Properties have (type, description)
|
||||
|
||||
## Stability ratings: 0-5
|
||||
|
||||
These can show up below any section heading, and apply to that section.
|
||||
|
||||
0 - Deprecated. This feature is known to be problematic, and changes are
|
||||
planned. Do not rely on it. Use of the feature may cause warnings. Backwards
|
||||
compatibility should not be expected.
|
||||
|
||||
1 - Experimental. This feature was introduced recently, and may change
|
||||
or be removed in future versions. Please try it out and provide feedback.
|
||||
If it addresses a use-case that is important to you, tell the node core team.
|
||||
|
||||
2 - Unstable. The API is in the process of settling, but has not yet had
|
||||
sufficient real-world testing to be considered stable. Backwards-compatibility
|
||||
will be maintained if reasonable.
|
||||
|
||||
3 - Stable. The API has proven satisfactory, but cleanup in the underlying
|
||||
code may cause minor changes. Backwards-compatibility is guaranteed.
|
||||
|
||||
4 - API Frozen. This API has been tested extensively in production and is
|
||||
unlikely to ever have to change.
|
||||
|
||||
5 - Locked. Unless serious bugs are found, this code will not ever
|
||||
change. Please do not suggest changes in this area, they will be refused.
|
||||
Executable
+99
@@ -0,0 +1,99 @@
|
||||
#!node
|
||||
|
||||
var marked = require('marked');
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
|
||||
// parse the args.
|
||||
// Don't use nopt or whatever for this. It's simple enough.
|
||||
|
||||
var args = process.argv.slice(2);
|
||||
var format = 'json';
|
||||
var template = null;
|
||||
var inputFile = null;
|
||||
|
||||
args.forEach(function (arg) {
|
||||
if (!arg.match(/^\-\-/)) {
|
||||
inputFile = arg;
|
||||
} else if (arg.match(/^\-\-format=/)) {
|
||||
format = arg.replace(/^\-\-format=/, '');
|
||||
} else if (arg.match(/^\-\-template=/)) {
|
||||
template = arg.replace(/^\-\-template=/, '');
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
if (!inputFile) {
|
||||
throw new Error('No input file specified');
|
||||
}
|
||||
|
||||
|
||||
console.error('Input file = %s', inputFile);
|
||||
fs.readFile(inputFile, 'utf8', function(er, input) {
|
||||
if (er) throw er;
|
||||
// process the input for @include lines
|
||||
processIncludes(input, next);
|
||||
});
|
||||
|
||||
|
||||
var includeExpr = /^@include\s+([A-Za-z0-9-_]+)(?:\.)?([a-zA-Z]*)$/gmi;
|
||||
var includeData = {};
|
||||
function processIncludes(input, cb) {
|
||||
var includes = input.match(includeExpr);
|
||||
if (includes === null) return cb(null, input);
|
||||
var errState = null;
|
||||
console.error(includes);
|
||||
var incCount = includes.length;
|
||||
if (incCount === 0) cb(null, input);
|
||||
includes.forEach(function(include) {
|
||||
var fname = include.replace(/^@include\s+/, '');
|
||||
if (!fname.match(/\.markdown$/)) fname += '.markdown';
|
||||
|
||||
if (includeData.hasOwnProperty(fname)) {
|
||||
input = input.split(include).join(includeData[fname]);
|
||||
incCount--;
|
||||
if (incCount === 0) {
|
||||
return cb(null, input);
|
||||
}
|
||||
}
|
||||
|
||||
var fullFname = path.resolve(path.dirname(inputFile), fname);
|
||||
fs.readFile(fullFname, 'utf8', function(er, inc) {
|
||||
if (errState) return;
|
||||
if (er) return cb(errState = er);
|
||||
processIncludes(inc, function(er, inc) {
|
||||
if (errState) return;
|
||||
if (er) return cb(errState = er);
|
||||
incCount--;
|
||||
includeData[fname] = inc;
|
||||
input = input.split(include).join(includeData[fname]);
|
||||
if (incCount === 0) {
|
||||
return cb(null, input);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function next(er, input) {
|
||||
if (er) throw er;
|
||||
switch (format) {
|
||||
case 'json':
|
||||
require('./json.js')(input, inputFile, function(er, obj) {
|
||||
console.log(JSON.stringify(obj, null, 2));
|
||||
if (er) throw er;
|
||||
});
|
||||
break;
|
||||
|
||||
case 'html':
|
||||
require('./html.js')(input, inputFile, template, function(er, html) {
|
||||
if (er) throw er;
|
||||
console.log(html);
|
||||
});
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error('Invalid format: ' + format);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
var fs = require('fs');
|
||||
var marked = require('marked');
|
||||
var path = require('path');
|
||||
|
||||
module.exports = toHTML;
|
||||
|
||||
function toHTML(input, filename, template, cb) {
|
||||
var lexed = marked.lexer(input);
|
||||
fs.readFile(template, 'utf8', function(er, template) {
|
||||
if (er) return cb(er);
|
||||
render(lexed, filename, template, cb);
|
||||
});
|
||||
}
|
||||
|
||||
function render(lexed, filename, template, cb) {
|
||||
// get the section
|
||||
var section = getSection(lexed);
|
||||
|
||||
filename = path.basename(filename, '.markdown');
|
||||
|
||||
lexed = parseLists(lexed);
|
||||
|
||||
// generate the table of contents.
|
||||
// this mutates the lexed contents in-place.
|
||||
buildToc(lexed, filename, function(er, toc) {
|
||||
if (er) return cb(er);
|
||||
|
||||
template = template.replace(/__FILENAME__/g, filename);
|
||||
template = template.replace(/__SECTION__/g, section);
|
||||
template = template.replace(/__VERSION__/g, process.version);
|
||||
template = template.replace(/__TOC__/g, toc);
|
||||
|
||||
// content has to be the last thing we do with
|
||||
// the lexed tokens, because it's destructive.
|
||||
content = marked.parser(lexed);
|
||||
template = template.replace(/__CONTENT__/g, content);
|
||||
|
||||
cb(null, template);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// just update the list item text in-place.
|
||||
// lists that come right after a heading are what we're after.
|
||||
function parseLists(input) {
|
||||
var state = null;
|
||||
var depth = 0;
|
||||
var output = [];
|
||||
output.links = input.links;
|
||||
input.forEach(function(tok) {
|
||||
if (state === null) {
|
||||
if (tok.type === 'heading') {
|
||||
state = 'AFTERHEADING';
|
||||
}
|
||||
output.push(tok);
|
||||
return;
|
||||
}
|
||||
if (state === 'AFTERHEADING') {
|
||||
if (tok.type === 'code') return;
|
||||
if (tok.type === 'list_start') {
|
||||
state = 'LIST';
|
||||
if (depth === 0) {
|
||||
output.push({ type:'html', text: '<div class="signature">' });
|
||||
}
|
||||
depth++;
|
||||
output.push(tok);
|
||||
return;
|
||||
}
|
||||
state = null;
|
||||
output.push(tok);
|
||||
return;
|
||||
}
|
||||
if (state === 'LIST') {
|
||||
if (tok.type === 'list_start') {
|
||||
depth++;
|
||||
output.push(tok);
|
||||
return;
|
||||
}
|
||||
if (tok.type === 'list_end') {
|
||||
depth--;
|
||||
if (depth === 0) {
|
||||
state = null;
|
||||
output.push({ type:'html', text: '</div>' });
|
||||
}
|
||||
output.push(tok);
|
||||
return;
|
||||
}
|
||||
if (tok.text) {
|
||||
tok.text = parseListItem(tok.text);
|
||||
}
|
||||
}
|
||||
output.push(tok);
|
||||
});
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
function parseListItem(text) {
|
||||
text = text.replace(/\{([^\}]+)\}/, '<span class="type">$1</span>');
|
||||
//XXX maybe put more stuff here?
|
||||
return text;
|
||||
}
|
||||
|
||||
|
||||
// section is just the first heading
|
||||
function getSection(lexed) {
|
||||
var section = '';
|
||||
for (var i = 0, l = lexed.length; i < l; i++) {
|
||||
var tok = lexed[i];
|
||||
if (tok.type === 'heading') return tok.text;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
|
||||
function buildToc(lexed, filename, cb) {
|
||||
var indent = 0;
|
||||
var toc = [];
|
||||
var depth = 0;
|
||||
lexed.forEach(function(tok) {
|
||||
if (tok.type !== 'heading') return;
|
||||
if (tok.depth - depth > 1) {
|
||||
return cb(new Error('Inappropriate heading level\n' +
|
||||
JSON.stringify(tok)));
|
||||
}
|
||||
|
||||
depth = tok.depth;
|
||||
var id = getId(filename + '_' + tok.text.trim());
|
||||
toc.push(new Array((depth - 1) * 2 + 1).join(' ') +
|
||||
'* <a href="#' + id + '">' +
|
||||
tok.text + '</a>');
|
||||
tok.text += '<span><a class="mark" href="#' + id + '" ' +
|
||||
'id="' + id + '">#</a></span>';
|
||||
});
|
||||
|
||||
toc = marked.parse(toc.join('\n'));
|
||||
cb(null, toc);
|
||||
}
|
||||
|
||||
var idCounters = {};
|
||||
function getId(text) {
|
||||
text = text.toLowerCase();
|
||||
text = text.replace(/[^a-z0-9]+/g, '_');
|
||||
text = text.replace(/^_+|_+$/, '');
|
||||
text = text.replace(/^([^a-z])/, '_$1');
|
||||
if (idCounters.hasOwnProperty(text)) {
|
||||
text += '_' + (++idCounters[text]);
|
||||
} else {
|
||||
idCounters[text] = 0;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,536 @@
|
||||
module.exports = doJSON;
|
||||
|
||||
// Take the lexed input, and return a JSON-encoded object
|
||||
// A module looks like this: https://gist.github.com/1777387
|
||||
|
||||
var marked = require('marked');
|
||||
|
||||
function doJSON(input, filename, cb) {
|
||||
var root = {source: filename};
|
||||
var stack = [root];
|
||||
var depth = 0;
|
||||
var current = root;
|
||||
var state = null;
|
||||
var lexed = marked.lexer(input);
|
||||
lexed.forEach(function (tok) {
|
||||
var type = tok.type;
|
||||
var text = tok.text;
|
||||
|
||||
// <!-- type = module -->
|
||||
// This is for cases where the markdown semantic structure is lacking.
|
||||
if (type === 'paragraph' || type === 'html') {
|
||||
var metaExpr = /<!--([^=]+)=([^\-]+)-->\n*/g;
|
||||
text = text.replace(metaExpr, function(_0, k, v) {
|
||||
current[k.trim()] = v.trim();
|
||||
return '';
|
||||
});
|
||||
text = text.trim();
|
||||
if (!text) return;
|
||||
}
|
||||
|
||||
if (type === 'heading' &&
|
||||
!text.trim().match(/^example/i)) {
|
||||
if (tok.depth - depth > 1) {
|
||||
return cb(new Error('Inappropriate heading level\n'+
|
||||
JSON.stringify(tok)));
|
||||
}
|
||||
|
||||
// Sometimes we have two headings with a single
|
||||
// blob of description. Treat as a clone.
|
||||
if (current &&
|
||||
state === 'AFTERHEADING' &&
|
||||
depth === tok.depth) {
|
||||
var clone = current;
|
||||
current = newSection(tok);
|
||||
current.clone = clone;
|
||||
// don't keep it around on the stack.
|
||||
stack.pop();
|
||||
} else {
|
||||
// if the level is greater than the current depth,
|
||||
// then it's a child, so we should just leave the stack
|
||||
// as it is.
|
||||
// However, if it's a sibling or higher, then it implies
|
||||
// the closure of the other sections that came before.
|
||||
// root is always considered the level=0 section,
|
||||
// and the lowest heading is 1, so this should always
|
||||
// result in having a valid parent node.
|
||||
var d = tok.depth;
|
||||
while (d <= depth) {
|
||||
finishSection(stack.pop(), stack[stack.length - 1]);
|
||||
d++;
|
||||
}
|
||||
current = newSection(tok);
|
||||
}
|
||||
|
||||
depth = tok.depth;
|
||||
stack.push(current);
|
||||
state = 'AFTERHEADING';
|
||||
return;
|
||||
} // heading
|
||||
|
||||
// Immediately after a heading, we can expect the following
|
||||
//
|
||||
// { type: 'code', text: 'Stability: ...' },
|
||||
//
|
||||
// a list: starting with list_start, ending with list_end,
|
||||
// maybe containing other nested lists in each item.
|
||||
//
|
||||
// If one of these isnt' found, then anything that comes between
|
||||
// here and the next heading should be parsed as the desc.
|
||||
var stability
|
||||
if (state === 'AFTERHEADING') {
|
||||
if (type === 'code' &&
|
||||
(stability = text.match(/^Stability: ([0-5])(?:\s*-\s*)?(.*)$/))) {
|
||||
current.stability = parseInt(stability[1], 10);
|
||||
current.stabilityText = stability[2].trim();
|
||||
return;
|
||||
} else if (type === 'list_start' && !tok.ordered) {
|
||||
state = 'AFTERHEADING_LIST';
|
||||
current.list = current.list || [];
|
||||
current.list.push(tok);
|
||||
current.list.level = 1;
|
||||
} else {
|
||||
current.desc = current.desc || [];
|
||||
if (!Array.isArray(current.desc)) {
|
||||
current.shortDesc = current.desc;
|
||||
current.desc = [];
|
||||
}
|
||||
current.desc.push(tok);
|
||||
state = 'DESC';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (state === 'AFTERHEADING_LIST') {
|
||||
current.list.push(tok);
|
||||
if (type === 'list_start') {
|
||||
current.list.level++;
|
||||
} else if (type === 'list_end') {
|
||||
current.list.level--;
|
||||
}
|
||||
if (current.list.level === 0) {
|
||||
state = 'AFTERHEADING';
|
||||
processList(current);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
current.desc = current.desc || [];
|
||||
current.desc.push(tok);
|
||||
|
||||
});
|
||||
|
||||
// finish any sections left open
|
||||
while (root !== (current = stack.pop())) {
|
||||
finishSection(current, stack[stack.length - 1]);
|
||||
}
|
||||
|
||||
return cb(null, root)
|
||||
}
|
||||
|
||||
|
||||
// go from something like this:
|
||||
// [ { type: 'list_item_start' },
|
||||
// { type: 'text',
|
||||
// text: '`settings` Object, Optional' },
|
||||
// { type: 'list_start', ordered: false },
|
||||
// { type: 'list_item_start' },
|
||||
// { type: 'text',
|
||||
// text: 'exec: String, file path to worker file. Default: `__filename`' },
|
||||
// { type: 'list_item_end' },
|
||||
// { type: 'list_item_start' },
|
||||
// { type: 'text',
|
||||
// text: 'args: Array, string arguments passed to worker.' },
|
||||
// { type: 'text',
|
||||
// text: 'Default: `process.argv.slice(2)`' },
|
||||
// { type: 'list_item_end' },
|
||||
// { type: 'list_item_start' },
|
||||
// { type: 'text',
|
||||
// text: 'silent: Boolean, whether or not to send output to parent\'s stdio.' },
|
||||
// { type: 'text', text: 'Default: `false`' },
|
||||
// { type: 'space' },
|
||||
// { type: 'list_item_end' },
|
||||
// { type: 'list_end' },
|
||||
// { type: 'list_item_end' },
|
||||
// { type: 'list_end' } ]
|
||||
// to something like:
|
||||
// [ { name: 'settings',
|
||||
// type: 'object',
|
||||
// optional: true,
|
||||
// settings:
|
||||
// [ { name: 'exec',
|
||||
// type: 'string',
|
||||
// desc: 'file path to worker file',
|
||||
// default: '__filename' },
|
||||
// { name: 'args',
|
||||
// type: 'array',
|
||||
// default: 'process.argv.slice(2)',
|
||||
// desc: 'string arguments passed to worker.' },
|
||||
// { name: 'silent',
|
||||
// type: 'boolean',
|
||||
// desc: 'whether or not to send output to parent\'s stdio.',
|
||||
// default: 'false' } ] } ]
|
||||
|
||||
function processList(section) {
|
||||
var list = section.list;
|
||||
var values = [];
|
||||
var current;
|
||||
var stack = [];
|
||||
|
||||
// for now, *just* build the heirarchical list
|
||||
list.forEach(function(tok) {
|
||||
var type = tok.type;
|
||||
if (type === 'space') return;
|
||||
if (type === 'list_item_start') {
|
||||
if (!current) {
|
||||
var n = {};
|
||||
values.push(n);
|
||||
current = n;
|
||||
} else {
|
||||
current.options = current.options || [];
|
||||
stack.push(current);
|
||||
var n = {};
|
||||
current.options.push(n);
|
||||
current = n;
|
||||
}
|
||||
return;
|
||||
} else if (type === 'list_item_end') {
|
||||
if (!current) {
|
||||
throw new Error('invalid list - end without current item\n' +
|
||||
JSON.stringify(tok) + '\n' +
|
||||
JSON.stringify(list));
|
||||
}
|
||||
current = stack.pop();
|
||||
} else if (type === 'text') {
|
||||
if (!current) {
|
||||
throw new Error('invalid list - text without current item\n' +
|
||||
JSON.stringify(tok) + '\n' +
|
||||
JSON.stringify(list));
|
||||
}
|
||||
current.textRaw = current.textRaw || '';
|
||||
current.textRaw += tok.text + ' ';
|
||||
}
|
||||
});
|
||||
|
||||
// shove the name in there for properties, since they are always
|
||||
// just going to be the value etc.
|
||||
if (section.type === 'property' && values[0]) {
|
||||
values[0].textRaw = '`' + section.name + '` ' + values[0].textRaw;
|
||||
}
|
||||
|
||||
// now pull the actual values out of the text bits.
|
||||
values.forEach(parseListItem);
|
||||
|
||||
// Now figure out what this list actually means.
|
||||
// depending on the section type, the list could be different things.
|
||||
|
||||
switch (section.type) {
|
||||
case 'ctor':
|
||||
case 'classMethod':
|
||||
case 'method':
|
||||
// each item is an argument, unless the name is 'return',
|
||||
// in which case it's the return value.
|
||||
section.signatures = section.signatures || [];
|
||||
var sig = {}
|
||||
section.signatures.push(sig);
|
||||
sig.params = values.filter(function(v) {
|
||||
if (v.name === 'return') {
|
||||
sig.return = v;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
parseSignature(section.textRaw, sig);
|
||||
break;
|
||||
|
||||
case 'property':
|
||||
// there should be only one item, which is the value.
|
||||
// copy the data up to the section.
|
||||
var value = values[0] || {};
|
||||
delete value.name;
|
||||
section.typeof = value.type;
|
||||
delete value.type;
|
||||
Object.keys(value).forEach(function(k) {
|
||||
section[k] = value[k];
|
||||
});
|
||||
break;
|
||||
|
||||
case 'event':
|
||||
// event: each item is an argument.
|
||||
section.params = values;
|
||||
break;
|
||||
}
|
||||
|
||||
// section.listParsed = values;
|
||||
delete section.list;
|
||||
}
|
||||
|
||||
|
||||
// textRaw = "someobject.someMethod(a, [b=100], [c])"
|
||||
function parseSignature(text, sig) {
|
||||
var params = text.match(paramExpr);
|
||||
if (!params) return;
|
||||
params = params[1];
|
||||
// the ] is irrelevant. [ indicates optionalness.
|
||||
params = params.replace(/\]/g, '');
|
||||
params = params.split(/,/)
|
||||
params.forEach(function(p, i, _) {
|
||||
p = p.trim();
|
||||
if (!p) return;
|
||||
var param = sig.params[i];
|
||||
var optional = false;
|
||||
var def;
|
||||
// [foo] -> optional
|
||||
if (p.charAt(0) === '[') {
|
||||
optional = true;
|
||||
p = p.substr(1);
|
||||
}
|
||||
var eq = p.indexOf('=');
|
||||
if (eq !== -1) {
|
||||
def = p.substr(eq + 1);
|
||||
p = p.substr(0, eq);
|
||||
}
|
||||
if (!param) {
|
||||
param = sig.params[i] = { name: p };
|
||||
}
|
||||
// at this point, the name should match.
|
||||
if (p !== param.name) {
|
||||
console.error('Warning: invalid param "%s"', p);
|
||||
console.error(' > ' + JSON.stringify(param));
|
||||
console.error(' > ' + text);
|
||||
}
|
||||
if (optional) param.optional = true;
|
||||
if (def !== undefined) param.default = def;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function parseListItem(item) {
|
||||
if (item.options) item.options.forEach(parseListItem);
|
||||
if (!item.textRaw) return;
|
||||
|
||||
// the goal here is to find the name, type, default, and optional.
|
||||
// anything left over is 'desc'
|
||||
var text = item.textRaw.trim();
|
||||
// text = text.replace(/^(Argument|Param)s?\s*:?\s*/i, '');
|
||||
|
||||
text = text.replace(/^, /, '').trim();
|
||||
var retExpr = /^returns?\s*:?\s*/i;
|
||||
var ret = text.match(retExpr);
|
||||
if (ret) {
|
||||
item.name = 'return';
|
||||
text = text.replace(retExpr, '');
|
||||
} else {
|
||||
var nameExpr = /^['`"]?([^'`": \{]+)['`"]?\s*:?\s*/;
|
||||
var name = text.match(nameExpr);
|
||||
if (name) {
|
||||
item.name = name[1];
|
||||
text = text.replace(nameExpr, '');
|
||||
}
|
||||
}
|
||||
|
||||
text = text.trim();
|
||||
var defaultExpr = /\(default\s*[:=]?\s*['"`]?([^, '"`]*)['"`]?\)/i;
|
||||
var def = text.match(defaultExpr);
|
||||
if (def) {
|
||||
item.default = def[1];
|
||||
text = text.replace(defaultExpr, '');
|
||||
}
|
||||
|
||||
text = text.trim();
|
||||
var typeExpr = /^\{([^\}]+)\}/;
|
||||
var type = text.match(typeExpr);
|
||||
if (type) {
|
||||
item.type = type[1];
|
||||
text = text.replace(typeExpr, '');
|
||||
}
|
||||
|
||||
text = text.trim();
|
||||
var optExpr = /^Optional\.|(?:, )?Optional$/;
|
||||
var optional = text.match(optExpr);
|
||||
if (optional) {
|
||||
item.optional = true;
|
||||
text = text.replace(optExpr, '');
|
||||
}
|
||||
|
||||
text = text.replace(/^\s*-\s*/, '');
|
||||
text = text.trim();
|
||||
if (text) item.desc = text;
|
||||
}
|
||||
|
||||
|
||||
function finishSection(section, parent) {
|
||||
if (!section || !parent) {
|
||||
throw new Error('Invalid finishSection call\n'+
|
||||
JSON.stringify(section) + '\n' +
|
||||
JSON.stringify(parent));
|
||||
}
|
||||
|
||||
if (!section.type) {
|
||||
section.type = 'module';
|
||||
if (parent && (parent.type === 'misc')) {
|
||||
section.type = 'misc';
|
||||
}
|
||||
section.displayName = section.name;
|
||||
section.name = section.name.toLowerCase()
|
||||
.trim().replace(/\s+/g, '_');
|
||||
}
|
||||
|
||||
if (section.desc && Array.isArray(section.desc)) {
|
||||
section.desc.links = section.desc.links || [];
|
||||
section.desc = marked.parser(section.desc);
|
||||
}
|
||||
|
||||
if (!section.list) section.list = [];
|
||||
processList(section);
|
||||
|
||||
// classes sometimes have various 'ctor' children
|
||||
// which are actually just descriptions of a constructor
|
||||
// class signature.
|
||||
// Merge them into the parent.
|
||||
if (section.type === 'class' && section.ctors) {
|
||||
section.signatures = section.signatures || [];
|
||||
var sigs = section.signatures;
|
||||
section.ctors.forEach(function(ctor) {
|
||||
ctor.signatures = ctor.signatures || [{}];
|
||||
ctor.signatures.forEach(function(sig) {
|
||||
sig.desc = ctor.desc;
|
||||
});
|
||||
sigs.push.apply(sigs, ctor.signatures);
|
||||
});
|
||||
delete section.ctors;
|
||||
}
|
||||
|
||||
// properties are a bit special.
|
||||
// their "type" is the type of object, not "property"
|
||||
if (section.properties) {
|
||||
section.properties.forEach(function (p) {
|
||||
if (p.typeof) p.type = p.typeof;
|
||||
else delete p.type;
|
||||
delete p.typeof;
|
||||
});
|
||||
}
|
||||
|
||||
// handle clones
|
||||
if (section.clone) {
|
||||
var clone = section.clone;
|
||||
delete section.clone;
|
||||
delete clone.clone;
|
||||
deepCopy(section, clone);
|
||||
finishSection(clone, parent);
|
||||
}
|
||||
|
||||
var plur;
|
||||
if (section.type.slice(-1) === 's') {
|
||||
plur = section.type + 'es';
|
||||
} else if (section.type.slice(-1) === 'y') {
|
||||
plur = section.type.replace(/y$/, 'ies');
|
||||
} else {
|
||||
plur = section.type + 's';
|
||||
}
|
||||
|
||||
// if the parent's type is 'misc', then it's just a random
|
||||
// collection of stuff, like the "globals" section.
|
||||
// Make the children top-level items.
|
||||
if (section.type === 'misc') {
|
||||
Object.keys(section).forEach(function(k) {
|
||||
switch (k) {
|
||||
case 'textRaw':
|
||||
case 'name':
|
||||
case 'type':
|
||||
case 'desc':
|
||||
case 'miscs':
|
||||
return;
|
||||
default:
|
||||
if (parent.type === 'misc') {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(k) && parent[k]) {
|
||||
parent[k] = parent[k].concat(section[k]);
|
||||
} else if (!parent[k]) {
|
||||
parent[k] = section[k];
|
||||
} else {
|
||||
// parent already has, and it's not an array.
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
parent[plur] = parent[plur] || [];
|
||||
parent[plur].push(section);
|
||||
}
|
||||
|
||||
|
||||
// Not a general purpose deep copy.
|
||||
// But sufficient for these basic things.
|
||||
function deepCopy(src, dest) {
|
||||
Object.keys(src).filter(function(k) {
|
||||
return !dest.hasOwnProperty(k);
|
||||
}).forEach(function(k) {
|
||||
dest[k] = deepCopy_(src[k]);
|
||||
});
|
||||
}
|
||||
|
||||
function deepCopy_(src) {
|
||||
if (!src) return src;
|
||||
if (Array.isArray(src)) {
|
||||
var c = new Array(src.length);
|
||||
src.forEach(function(v, i) {
|
||||
c[i] = deepCopy_(v);
|
||||
});
|
||||
return c;
|
||||
}
|
||||
if (typeof src === 'object') {
|
||||
var c = {};
|
||||
Object.keys(src).forEach(function(k) {
|
||||
c[k] = deepCopy_(src[k]);
|
||||
});
|
||||
return c;
|
||||
}
|
||||
return src;
|
||||
}
|
||||
|
||||
|
||||
// these parse out the contents of an H# tag
|
||||
var eventExpr = /^Event(?::|\s)+['"]?([^"']+).*$/i;
|
||||
var classExpr = /^Class:\s*([^ ]+).*?$/i;
|
||||
var propExpr = /^(?:property:?\s*)?[^\.]+\.([^ \.\(\)]+)\s*?$/i;
|
||||
var braceExpr = /^(?:property:?\s*)?[^\.\[]+(\[[^\]]+\])\s*?$/i;
|
||||
var classMethExpr =
|
||||
/^class\s*method\s*:?[^\.]+\.([^ \.\(\)]+)\([^\)]*\)\s*?$/i;
|
||||
var methExpr =
|
||||
/^(?:method:?\s*)?(?:[^\.]+\.)?([^ \.\(\)]+)\([^\)]*\)\s*?$/i;
|
||||
var newExpr = /^new ([A-Z][a-z]+)\([^\)]*\)\s*?$/;
|
||||
var paramExpr = /\((.*)\);?$/;
|
||||
|
||||
function newSection(tok) {
|
||||
var section = {};
|
||||
// infer the type from the text.
|
||||
var text = section.textRaw = tok.text;
|
||||
if (text.match(eventExpr)) {
|
||||
section.type = 'event';
|
||||
section.name = text.replace(eventExpr, '$1');
|
||||
} else if (text.match(classExpr)) {
|
||||
section.type = 'class';
|
||||
section.name = text.replace(classExpr, '$1');
|
||||
} else if (text.match(braceExpr)) {
|
||||
section.type = 'property';
|
||||
section.name = text.replace(braceExpr, '$1');
|
||||
} else if (text.match(propExpr)) {
|
||||
section.type = 'property';
|
||||
section.name = text.replace(propExpr, '$1');
|
||||
} else if (text.match(classMethExpr)) {
|
||||
section.type = 'classMethod';
|
||||
section.name = text.replace(classMethExpr, '$1');
|
||||
} else if (text.match(methExpr)) {
|
||||
section.type = 'method';
|
||||
section.name = text.replace(methExpr, '$1');
|
||||
} else if (text.match(newExpr)) {
|
||||
section.type = 'ctor';
|
||||
section.name = text.replace(newExpr, '$1');
|
||||
} else {
|
||||
section.name = text;
|
||||
}
|
||||
return section;
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
../marked/bin/marked
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
.git*
|
||||
test/
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
Copyright (c) 2011-2012, Christopher Jeffrey (https://github.com/chjj/)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
all:
|
||||
@cp lib/marked.js marked.js
|
||||
@uglifyjs -o marked.min.js marked.js
|
||||
|
||||
clean:
|
||||
@rm marked.js
|
||||
@rm marked.min.js
|
||||
|
||||
.PHONY: clean all
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
# marked
|
||||
|
||||
A full-featured markdown parser and compiler.
|
||||
Built for speed.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
node v0.4.x
|
||||
|
||||
``` bash
|
||||
$ node test --bench
|
||||
marked completed in 12071ms.
|
||||
showdown (reuse converter) completed in 27387ms.
|
||||
showdown (new converter) completed in 75617ms.
|
||||
markdown-js completed in 70069ms.
|
||||
```
|
||||
|
||||
node v0.6.x
|
||||
|
||||
``` bash
|
||||
$ node test --bench
|
||||
marked completed in 6485ms.
|
||||
marked (with gfm) completed in 7466ms.
|
||||
discount completed in 7169ms.
|
||||
showdown (reuse converter) completed in 15937ms.
|
||||
showdown (new converter) completed in 18279ms.
|
||||
markdown-js completed in 23572ms.
|
||||
```
|
||||
|
||||
__Marked is now faster than Discount, which is written in C.__
|
||||
|
||||
For those feeling skeptical: These benchmarks run the entire markdown test suite
|
||||
1000 times. The test suite tests every feature. It doesn't cater to specific
|
||||
aspects.
|
||||
|
||||
Benchmarks for other engines to come (?).
|
||||
|
||||
## Install
|
||||
|
||||
``` bash
|
||||
$ npm install marked
|
||||
```
|
||||
|
||||
## Another javascript markdown parser
|
||||
|
||||
The point of marked was to create a markdown compiler where it was possible to
|
||||
frequently parse huge chunks of markdown without having to worry about
|
||||
caching the compiled output somehow...or blocking for an unnecesarily long time.
|
||||
|
||||
marked is very concise and still implements all markdown features. It is also
|
||||
now fully compatible with the client-side.
|
||||
|
||||
marked more or less passes the official markdown test suite in its
|
||||
entirety. This is important because a surprising number of markdown compilers
|
||||
cannot pass more than a few tests. It was very difficult to get marked as
|
||||
compliant as it is. It could have cut corners in several areas for the sake
|
||||
of performance, but did not in order to be exactly what you expect in terms
|
||||
of a markdown rendering. In fact, this is why marked could be considered at a
|
||||
disadvantage in the benchmarks above.
|
||||
|
||||
Along with implementing every markdown feature, marked also implements
|
||||
[GFM features](http://github.github.com/github-flavored-markdown/).
|
||||
|
||||
## Usage
|
||||
|
||||
``` js
|
||||
var marked = require('marked');
|
||||
console.log(marked('i am using __markdown__.'));
|
||||
```
|
||||
|
||||
You also have direct access to the lexer and parser if you so desire.
|
||||
|
||||
``` js
|
||||
var tokens = marked.lexer(str);
|
||||
console.log(marked.parser(tokens));
|
||||
```
|
||||
|
||||
``` bash
|
||||
$ node
|
||||
> require('marked').lexer('> i am using marked.')
|
||||
[ { type: 'blockquote_start' },
|
||||
{ type: 'text', text: ' i am using marked.' },
|
||||
{ type: 'blockquote_end' },
|
||||
links: {} ]
|
||||
```
|
||||
|
||||
## CLI
|
||||
|
||||
``` bash
|
||||
$ marked -o hello.html
|
||||
hello world
|
||||
^D
|
||||
$ cat hello.html
|
||||
<p>hello world</p>
|
||||
```
|
||||
|
||||
## Syntax Highlighting
|
||||
|
||||
Marked has an interface that allows for a syntax highlighter to highlight code
|
||||
blocks before they're output.
|
||||
|
||||
Example implementation:
|
||||
|
||||
``` js
|
||||
var highlight = require('my-syntax-highlighter')
|
||||
, marked_ = require('marked');
|
||||
|
||||
var marked = function(text) {
|
||||
var tokens = marked_.lexer(text)
|
||||
, l = tokens.length
|
||||
, i = 0
|
||||
, token;
|
||||
|
||||
for (; i < l; i++) {
|
||||
token = tokens[i];
|
||||
if (token.type === 'code') {
|
||||
token.text = highlight(token.text, token.lang);
|
||||
// marked should not escape this
|
||||
token.escaped = true;
|
||||
}
|
||||
}
|
||||
|
||||
text = marked_.parser(tokens);
|
||||
|
||||
return text;
|
||||
};
|
||||
|
||||
module.exports = marked;
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Copyright (c) 2011-2012, Christopher Jeffrey. (MIT License)
|
||||
|
||||
See LICENSE for more info.
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Marked CLI
|
||||
* Copyright (c) 2011-2012, Christopher Jeffrey (MIT License)
|
||||
*/
|
||||
|
||||
var fs = require('fs')
|
||||
, util = require('util')
|
||||
, marked = require('../');
|
||||
|
||||
/**
|
||||
* Man Page
|
||||
*/
|
||||
|
||||
var help = function() {
|
||||
var spawn = require('child_process').spawn;
|
||||
|
||||
var options = {
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
setsid: false,
|
||||
customFds: [0, 1, 2]
|
||||
};
|
||||
|
||||
spawn('man',
|
||||
[__dirname + '/../man/marked.1'],
|
||||
options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Main
|
||||
*/
|
||||
|
||||
var main = function(argv) {
|
||||
var files = []
|
||||
, data = ''
|
||||
, input
|
||||
, output
|
||||
, arg
|
||||
, tokens;
|
||||
|
||||
var getarg = function() {
|
||||
var arg = argv.shift();
|
||||
arg = arg.split('=');
|
||||
if (arg.length > 1) {
|
||||
argv.unshift(arg.slice(1).join('='));
|
||||
}
|
||||
return arg[0];
|
||||
};
|
||||
|
||||
while (argv.length) {
|
||||
arg = getarg();
|
||||
switch (arg) {
|
||||
case '-o':
|
||||
case '--output':
|
||||
output = argv.shift();
|
||||
break;
|
||||
case '-i':
|
||||
case '--input':
|
||||
input = argv.shift();
|
||||
break;
|
||||
case '-t':
|
||||
case '--tokens':
|
||||
tokens = true;
|
||||
break;
|
||||
case '-h':
|
||||
case '--help':
|
||||
return help();
|
||||
default:
|
||||
files.push(arg);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!input) {
|
||||
if (files.length <= 2) {
|
||||
var stdin = process.stdin;
|
||||
|
||||
stdin.setEncoding('utf8');
|
||||
stdin.resume();
|
||||
|
||||
stdin.on('data', function(text) {
|
||||
data += text;
|
||||
});
|
||||
|
||||
stdin.on('end', write);
|
||||
|
||||
return;
|
||||
}
|
||||
input = files.pop();
|
||||
}
|
||||
|
||||
data = fs.readFileSync(input, 'utf8');
|
||||
write();
|
||||
|
||||
function write() {
|
||||
data = tokens
|
||||
? JSON.stringify(marked.lexer(data), null, 2)
|
||||
: marked(data);
|
||||
|
||||
if (!output) {
|
||||
process.stdout.write(data + '\n');
|
||||
} else {
|
||||
fs.writeFileSync(output, data);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (!module.parent) {
|
||||
process.title = 'marked';
|
||||
main(process.argv.slice());
|
||||
} else {
|
||||
module.exports = main;
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require('./lib/marked');
|
||||
+662
@@ -0,0 +1,662 @@
|
||||
/**
|
||||
* marked - A markdown parser (https://github.com/chjj/marked)
|
||||
* Copyright (c) 2011-2012, Christopher Jeffrey. (MIT Licensed)
|
||||
*/
|
||||
|
||||
;(function() {
|
||||
|
||||
/**
|
||||
* Block-Level Grammar
|
||||
*/
|
||||
|
||||
var block = {
|
||||
newline: /^\n+/,
|
||||
code: /^ {4,}[^\n]*(?:\n {4,}[^\n]*|\n)*(?:\n+|$)/,
|
||||
gfm_code: /^ *``` *(\w+)? *\n([^\0]+?)\s*``` *(?:\n+|$)/,
|
||||
hr: /^( *[\-*_]){3,} *(?:\n+|$)/,
|
||||
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
|
||||
lheading: /^([^\n]+)\n *(=|-){3,} *\n*/,
|
||||
blockquote: /^( *>[^\n]+(\n[^\n]+)*\n*)+/,
|
||||
list: /^( *)([*+-]|\d+\.) [^\0]+?(?:\n{2,}(?! )|\s*$)(?!\1bullet)\n*/,
|
||||
html: /^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/,
|
||||
def: /^ *\[([^\]]+)\]: *([^\s]+)(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
|
||||
paragraph: /^([^\n]+\n?(?!body))+\n*/,
|
||||
text: /^[^\n]+/
|
||||
};
|
||||
|
||||
block.list = (function() {
|
||||
var list = block.list.source;
|
||||
|
||||
list = list
|
||||
.replace('bullet', /(?:[*+-](?!(?: *[-*]){2,})|\d+\.)/.source);
|
||||
|
||||
return new RegExp(list);
|
||||
})();
|
||||
|
||||
block.html = (function() {
|
||||
var html = block.html.source;
|
||||
|
||||
html = html
|
||||
.replace('comment', /<!--[^\0]*?-->/.source)
|
||||
.replace('closed', /<(tag)[^\0]+?<\/\1>/.source)
|
||||
.replace('closing', /<tag(?!:\/|@)\b(?:"[^"]*"|'[^']*'|[^'">])*?>/.source)
|
||||
.replace(/tag/g, tag());
|
||||
|
||||
return new RegExp(html);
|
||||
})();
|
||||
|
||||
block.paragraph = (function() {
|
||||
var paragraph = block.paragraph.source
|
||||
, body = [];
|
||||
|
||||
(function push(rule) {
|
||||
rule = block[rule] ? block[rule].source : rule;
|
||||
body.push(rule.replace(/(^|[^\[])\^/g, '$1'));
|
||||
return push;
|
||||
})
|
||||
('gfm_code')
|
||||
('hr')
|
||||
('heading')
|
||||
('lheading')
|
||||
('blockquote')
|
||||
('<' + tag())
|
||||
('def');
|
||||
|
||||
return new
|
||||
RegExp(paragraph.replace('body', body.join('|')));
|
||||
})();
|
||||
|
||||
/**
|
||||
* Block Lexer
|
||||
*/
|
||||
|
||||
block.lexer = function(src) {
|
||||
var tokens = [];
|
||||
|
||||
tokens.links = {};
|
||||
|
||||
src = src
|
||||
.replace(/\r\n|\r/g, '\n')
|
||||
.replace(/\t/g, ' ');
|
||||
|
||||
return block.token(src, tokens, true);
|
||||
};
|
||||
|
||||
block.token = function(src, tokens, top) {
|
||||
var src = src.replace(/^ +$/gm, '')
|
||||
, next
|
||||
, loose
|
||||
, cap
|
||||
, item
|
||||
, space
|
||||
, i
|
||||
, l;
|
||||
|
||||
while (src) {
|
||||
// newline
|
||||
if (cap = block.newline.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
if (cap[0].length > 1) {
|
||||
tokens.push({
|
||||
type: 'space'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// code
|
||||
if (cap = block.code.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
cap = cap[0].replace(/^ {4}/gm, '');
|
||||
tokens.push({
|
||||
type: 'code',
|
||||
text: cap.replace(/\n+$/, '')
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// gfm_code
|
||||
if (cap = block.gfm_code.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
tokens.push({
|
||||
type: 'code',
|
||||
lang: cap[1],
|
||||
text: cap[2]
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// heading
|
||||
if (cap = block.heading.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
tokens.push({
|
||||
type: 'heading',
|
||||
depth: cap[1].length,
|
||||
text: cap[2]
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// lheading
|
||||
if (cap = block.lheading.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
tokens.push({
|
||||
type: 'heading',
|
||||
depth: cap[2] === '=' ? 1 : 2,
|
||||
text: cap[1]
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// hr
|
||||
if (cap = block.hr.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
tokens.push({
|
||||
type: 'hr'
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// blockquote
|
||||
if (cap = block.blockquote.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
tokens.push({
|
||||
type: 'blockquote_start'
|
||||
});
|
||||
|
||||
cap = cap[0].replace(/^ *> ?/gm, '');
|
||||
|
||||
// Pass `top` to keep the current
|
||||
// "toplevel" state. This is exactly
|
||||
// how markdown.pl works.
|
||||
block.token(cap, tokens, top);
|
||||
|
||||
tokens.push({
|
||||
type: 'blockquote_end'
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// list
|
||||
if (cap = block.list.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
|
||||
tokens.push({
|
||||
type: 'list_start',
|
||||
ordered: isFinite(cap[2])
|
||||
});
|
||||
|
||||
// Get each top-level item.
|
||||
cap = cap[0].match(
|
||||
/^( *)([*+-]|\d+\.)[^\n]*(?:\n(?!\1(?:[*+-]|\d+\.))[^\n]*)*/gm
|
||||
);
|
||||
|
||||
next = false;
|
||||
l = cap.length;
|
||||
i = 0;
|
||||
|
||||
for (; i < l; i++) {
|
||||
item = cap[i];
|
||||
|
||||
// Remove the list item's bullet
|
||||
// so it is seen as the next token.
|
||||
space = item.length;
|
||||
item = item.replace(/^ *([*+-]|\d+\.) */, '');
|
||||
|
||||
// Outdent whatever the
|
||||
// list item contains. Hacky.
|
||||
if (~item.indexOf('\n ')) {
|
||||
space -= item.length;
|
||||
item = item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '');
|
||||
}
|
||||
|
||||
// Determine whether item is loose or not.
|
||||
// Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
|
||||
// for discount behavior.
|
||||
loose = next || /\n\n(?!\s*$)/.test(item);
|
||||
if (i !== l - 1) {
|
||||
next = item[item.length-1] === '\n';
|
||||
if (!loose) loose = next;
|
||||
}
|
||||
|
||||
tokens.push({
|
||||
type: loose
|
||||
? 'loose_item_start'
|
||||
: 'list_item_start'
|
||||
});
|
||||
|
||||
// Recurse.
|
||||
block.token(item, tokens);
|
||||
|
||||
tokens.push({
|
||||
type: 'list_item_end'
|
||||
});
|
||||
}
|
||||
|
||||
tokens.push({
|
||||
type: 'list_end'
|
||||
});
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// html
|
||||
if (cap = block.html.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
tokens.push({
|
||||
type: 'html',
|
||||
text: cap[0]
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// def
|
||||
if (top && (cap = block.def.exec(src))) {
|
||||
src = src.substring(cap[0].length);
|
||||
tokens.links[cap[1].toLowerCase()] = {
|
||||
href: cap[2],
|
||||
title: cap[3]
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
// top-level paragraph
|
||||
if (top && (cap = block.paragraph.exec(src))) {
|
||||
src = src.substring(cap[0].length);
|
||||
tokens.push({
|
||||
type: 'paragraph',
|
||||
text: cap[0]
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// text
|
||||
if (cap = block.text.exec(src)) {
|
||||
// Top-level should never reach here.
|
||||
src = src.substring(cap[0].length);
|
||||
tokens.push({
|
||||
type: 'text',
|
||||
text: cap[0]
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return tokens;
|
||||
};
|
||||
|
||||
/**
|
||||
* Inline Processing
|
||||
*/
|
||||
|
||||
var inline = {
|
||||
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
|
||||
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
|
||||
gfm_autolink: /^(\w+:\/\/[^\s]+[^.,:;"')\]\s])/,
|
||||
tag: /^<!--[^\0]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
|
||||
link: /^!?\[((?:\[[^\]]*\]|[^\[\]]|\[|\](?=[^[\]]*\]))*)\]\(([^\)]*)\)/,
|
||||
reflink: /^!?\[((?:\[[^\]]*\]|[^\[\]]|\[|\](?=[^[\]]*\]))*)\]\s*\[([^\]]*)\]/,
|
||||
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
|
||||
strong: /^__([^\0]+?)__(?!_)|^\*\*([^\0]+?)\*\*(?!\*)/,
|
||||
em: /^\b_([^\0]+?)_\b|^\*((?:\*\*|[^\0])+?)\*(?!\*)/,
|
||||
code: /^(`+)([^\0]*?[^`])\1(?!`)/,
|
||||
br: /^ {2,}\n(?!\s*$)/,
|
||||
text: /^[^\0]+?(?=[\\<!\[_*`]|\w+:\/\/| {2,}\n|$)/
|
||||
};
|
||||
|
||||
/**
|
||||
* Inline Lexer
|
||||
*/
|
||||
|
||||
inline.lexer = function(src) {
|
||||
var out = ''
|
||||
, links = tokens.links
|
||||
, link
|
||||
, text
|
||||
, href
|
||||
, cap;
|
||||
|
||||
while (src) {
|
||||
// escape
|
||||
if (cap = inline.escape.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
out += cap[1];
|
||||
continue;
|
||||
}
|
||||
|
||||
// autolink
|
||||
if (cap = inline.autolink.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
if (cap[2] === '@') {
|
||||
text = cap[1][6] === ':'
|
||||
? mangle(cap[1].substring(7))
|
||||
: mangle(cap[1]);
|
||||
href = mangle('mailto:') + text;
|
||||
} else {
|
||||
text = escape(cap[1]);
|
||||
href = text;
|
||||
}
|
||||
out += '<a href="'
|
||||
+ href
|
||||
+ '">'
|
||||
+ text
|
||||
+ '</a>';
|
||||
continue;
|
||||
}
|
||||
|
||||
// gfm_autolink
|
||||
if (cap = inline.gfm_autolink.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
text = escape(cap[1]);
|
||||
href = text;
|
||||
out += '<a href="'
|
||||
+ href
|
||||
+ '">'
|
||||
+ text
|
||||
+ '</a>';
|
||||
continue;
|
||||
}
|
||||
|
||||
// tag
|
||||
if (cap = inline.tag.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
out += cap[0];
|
||||
continue;
|
||||
}
|
||||
|
||||
// link
|
||||
if (cap = inline.link.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
text = /^\s*<?([^\s]*?)>?(?:\s+"([^\n]+)")?\s*$/.exec(cap[2]);
|
||||
if (!text) {
|
||||
out += cap[0][0];
|
||||
src = cap[0].substring(1) + src;
|
||||
continue;
|
||||
}
|
||||
out += outputLink(cap, {
|
||||
href: text[1],
|
||||
title: text[2]
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// reflink, nolink
|
||||
if ((cap = inline.reflink.exec(src))
|
||||
|| (cap = inline.nolink.exec(src))) {
|
||||
src = src.substring(cap[0].length);
|
||||
link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
|
||||
link = links[link.toLowerCase()];
|
||||
if (!link || !link.href) {
|
||||
out += cap[0][0];
|
||||
src = cap[0].substring(1) + src;
|
||||
continue;
|
||||
}
|
||||
out += outputLink(cap, link);
|
||||
continue;
|
||||
}
|
||||
|
||||
// strong
|
||||
if (cap = inline.strong.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
out += '<strong>'
|
||||
+ inline.lexer(cap[2] || cap[1])
|
||||
+ '</strong>';
|
||||
continue;
|
||||
}
|
||||
|
||||
// em
|
||||
if (cap = inline.em.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
out += '<em>'
|
||||
+ inline.lexer(cap[2] || cap[1])
|
||||
+ '</em>';
|
||||
continue;
|
||||
}
|
||||
|
||||
// code
|
||||
if (cap = inline.code.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
out += '<code>'
|
||||
+ escape(cap[2], true)
|
||||
+ '</code>';
|
||||
continue;
|
||||
}
|
||||
|
||||
// br
|
||||
if (cap = inline.br.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
out += '<br>';
|
||||
continue;
|
||||
}
|
||||
|
||||
// text
|
||||
if (cap = inline.text.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
out += escape(cap[0]);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
};
|
||||
|
||||
var outputLink = function(cap, link) {
|
||||
if (cap[0][0] !== '!') {
|
||||
return '<a href="'
|
||||
+ escape(link.href)
|
||||
+ '"'
|
||||
+ (link.title
|
||||
? ' title="'
|
||||
+ escape(link.title)
|
||||
+ '"'
|
||||
: '')
|
||||
+ '>'
|
||||
+ inline.lexer(cap[1])
|
||||
+ '</a>';
|
||||
} else {
|
||||
return '<img src="'
|
||||
+ escape(link.href)
|
||||
+ '" alt="'
|
||||
+ escape(cap[1])
|
||||
+ '"'
|
||||
+ (link.title
|
||||
? ' title="'
|
||||
+ escape(link.title)
|
||||
+ '"'
|
||||
: '')
|
||||
+ '>';
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Parsing
|
||||
*/
|
||||
|
||||
var tokens
|
||||
, token;
|
||||
|
||||
var next = function() {
|
||||
return token = tokens.pop();
|
||||
};
|
||||
|
||||
var tok = function() {
|
||||
switch (token.type) {
|
||||
case 'space': {
|
||||
return '';
|
||||
}
|
||||
case 'hr': {
|
||||
return '<hr>\n';
|
||||
}
|
||||
case 'heading': {
|
||||
return '<h'
|
||||
+ token.depth
|
||||
+ '>'
|
||||
+ inline.lexer(token.text)
|
||||
+ '</h'
|
||||
+ token.depth
|
||||
+ '>\n';
|
||||
}
|
||||
case 'code': {
|
||||
return '<pre><code'
|
||||
+ (token.lang
|
||||
? ' class="'
|
||||
+ token.lang
|
||||
+ '"'
|
||||
: '')
|
||||
+ '>'
|
||||
+ (token.escaped
|
||||
? token.text
|
||||
: escape(token.text, true))
|
||||
+ '</code></pre>\n';
|
||||
}
|
||||
case 'blockquote_start': {
|
||||
var body = '';
|
||||
|
||||
while (next().type !== 'blockquote_end') {
|
||||
body += tok();
|
||||
}
|
||||
|
||||
return '<blockquote>\n'
|
||||
+ body
|
||||
+ '</blockquote>\n';
|
||||
}
|
||||
case 'list_start': {
|
||||
var type = token.ordered ? 'ol' : 'ul'
|
||||
, body = '';
|
||||
|
||||
while (next().type !== 'list_end') {
|
||||
body += tok();
|
||||
}
|
||||
|
||||
return '<'
|
||||
+ type
|
||||
+ '>\n'
|
||||
+ body
|
||||
+ '</'
|
||||
+ type
|
||||
+ '>\n';
|
||||
}
|
||||
case 'list_item_start': {
|
||||
var body = '';
|
||||
|
||||
while (next().type !== 'list_item_end') {
|
||||
body += token.type === 'text'
|
||||
? parseText()
|
||||
: tok();
|
||||
}
|
||||
|
||||
return '<li>'
|
||||
+ body
|
||||
+ '</li>\n';
|
||||
}
|
||||
case 'loose_item_start': {
|
||||
var body = '';
|
||||
|
||||
while (next().type !== 'list_item_end') {
|
||||
body += tok();
|
||||
}
|
||||
|
||||
return '<li>'
|
||||
+ body
|
||||
+ '</li>\n';
|
||||
}
|
||||
case 'html': {
|
||||
return inline.lexer(token.text);
|
||||
}
|
||||
case 'paragraph': {
|
||||
return '<p>'
|
||||
+ inline.lexer(token.text)
|
||||
+ '</p>\n';
|
||||
}
|
||||
case 'text': {
|
||||
return '<p>'
|
||||
+ parseText()
|
||||
+ '</p>\n';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var parseText = function() {
|
||||
var body = token.text
|
||||
, top;
|
||||
|
||||
while ((top = tokens[tokens.length-1])
|
||||
&& top.type === 'text') {
|
||||
body += '\n' + next().text;
|
||||
}
|
||||
|
||||
return inline.lexer(body);
|
||||
};
|
||||
|
||||
var parse = function(src) {
|
||||
tokens = src.reverse();
|
||||
|
||||
var out = '';
|
||||
while (next()) {
|
||||
out += tok();
|
||||
}
|
||||
|
||||
tokens = null;
|
||||
token = null;
|
||||
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* Helpers
|
||||
*/
|
||||
|
||||
var escape = function(html, encode) {
|
||||
return html
|
||||
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
};
|
||||
|
||||
var mangle = function(text) {
|
||||
var out = ''
|
||||
, l = text.length
|
||||
, i = 0
|
||||
, ch;
|
||||
|
||||
for (; i < l; i++) {
|
||||
ch = text.charCodeAt(i);
|
||||
if (Math.random() > 0.5) {
|
||||
ch = 'x' + ch.toString(16);
|
||||
}
|
||||
out += '&#' + ch + ';';
|
||||
}
|
||||
|
||||
return out;
|
||||
};
|
||||
|
||||
function tag() {
|
||||
var tag = '(?!(?:'
|
||||
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
|
||||
+ '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
|
||||
+ '|span|br|wbr|ins|del|img)\\b)\\w+';
|
||||
|
||||
return tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expose
|
||||
*/
|
||||
|
||||
var marked = function(src) {
|
||||
return parse(block.lexer(src));
|
||||
};
|
||||
|
||||
marked.parser = parse;
|
||||
marked.lexer = block.lexer;
|
||||
|
||||
marked.parse = marked;
|
||||
|
||||
if (typeof module !== 'undefined') {
|
||||
module.exports = marked;
|
||||
} else {
|
||||
this.marked = marked;
|
||||
}
|
||||
|
||||
}).call(this);
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
.ds q \N'34'
|
||||
.TH marked 1
|
||||
.SH NAME
|
||||
marked \- a javascript markdown parser
|
||||
.SH SYNOPSIS
|
||||
.nf
|
||||
.B marked [\-o output] [\-i input] [\-th]
|
||||
.fi
|
||||
.SH DESCRIPTION
|
||||
.B marked
|
||||
is a full-featured javascript markdown parser, built for speed. It also includes
|
||||
multiple GFM features.
|
||||
.SH OPTIONS
|
||||
.TP
|
||||
.BI \-o,\ \-\-output\ [output]
|
||||
Specify file output. If none is specified, write to stdout.
|
||||
.TP
|
||||
.BI \-i,\ \-\-input\ [input]
|
||||
Specify file input, otherwise use last argument as input file. If no input file
|
||||
is specified, read from stdin.
|
||||
.TP
|
||||
.BI \-t,\ \-\-tokens
|
||||
Output a token stream instead of html.
|
||||
.TP
|
||||
.BI \-h,\ \-\-help
|
||||
Display help information.
|
||||
.SH EXAMPLES
|
||||
.TP
|
||||
cat in.md | marked > out.html
|
||||
.TP
|
||||
echo "hello *world*" | marked
|
||||
.TP
|
||||
marked -o out.html in.md
|
||||
.TP
|
||||
marked --output="hello world.html" -i in.md
|
||||
.SH BUGS
|
||||
Please report any bugs to https://github.com/chjj/marked.
|
||||
.SH LICENSE
|
||||
Copyright (c) 2011-2012, Christopher Jeffrey (MIT License)
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "marked",
|
||||
"description": "A markdown parser built for speed",
|
||||
"author": "Christopher Jeffrey",
|
||||
"version": "0.1.9",
|
||||
"main": "./lib/marked.js",
|
||||
"bin": "./bin/marked",
|
||||
"man": "./man/marked.1",
|
||||
"preferGlobal": false,
|
||||
"repository": "git://github.com/chjj/marked.git",
|
||||
"homepage": "https://github.com/chjj/marked",
|
||||
"bugs": "http://github.com/chjj/marked/issues",
|
||||
"keywords": [ "markdown", "markup", "html" ],
|
||||
"tags": [ "markdown", "markup", "html" ]
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)",
|
||||
"name": "node-doc-generator",
|
||||
"description": "Internal tool for generating Node.js API docs",
|
||||
"version": "0.0.0",
|
||||
"engines": {
|
||||
"node": ">=0.6.10"
|
||||
},
|
||||
"dependencies": {
|
||||
"marked": "~0.1.9"
|
||||
},
|
||||
"devDependencies": {},
|
||||
"optionalDependencies": {},
|
||||
"bin": "./generate.js"
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
/*
|
||||
Process a single doc file
|
||||
|
||||
argv[2] = template file
|
||||
argv[3] = input file
|
||||
argv[4] = output file
|
||||
|
||||
*/
|
||||
var fs = require("fs"),
|
||||
path = require("path"),
|
||||
markdown = require("./markdown"),
|
||||
argv = process.argv,
|
||||
argc = argv.length;
|
||||
|
||||
var template = fs.readFileSync(argv[2], "utf8");
|
||||
|
||||
|
||||
function formatIdString(str) {
|
||||
str = str
|
||||
.replace(/\([^)}]*\)/gmi, "")
|
||||
.replace(/[^A-Za-z0-9_.]+/gmi, "_");
|
||||
|
||||
return str.substr(0,1).toLowerCase() + str.substr(1);
|
||||
}
|
||||
|
||||
|
||||
function generateToc(data) {
|
||||
var last_level = 0
|
||||
, first_level = 0
|
||||
, toc = [
|
||||
'<div id="toc">',
|
||||
'<h2>Table Of Contents</h2>'
|
||||
];
|
||||
|
||||
data.replace(/(^#+)\W+([^$\n]+)/gmi, function(src, level, text) {
|
||||
level = level.length;
|
||||
|
||||
if (first_level == 0) first_level = level;
|
||||
|
||||
if (level <= last_level) {
|
||||
toc.push("</li>");
|
||||
}
|
||||
|
||||
if (level > last_level) {
|
||||
var c = last_level - level;
|
||||
do {
|
||||
toc.push("<ul>");
|
||||
c ++;
|
||||
} while (c < -1);
|
||||
} else if (level < last_level) {
|
||||
for(var c=last_level-level; 0 < c ; c-- ) {
|
||||
toc.push("</ul>");
|
||||
toc.push("</li>");
|
||||
}
|
||||
}
|
||||
|
||||
toc.push("<li>");
|
||||
toc.push('<a href="#'+formatIdString(text)+'">'+text+'</a>');
|
||||
|
||||
last_level = level;
|
||||
});
|
||||
|
||||
for(var c=last_level-first_level; 0 <= c ; c-- ) {
|
||||
toc.push("</li>");
|
||||
toc.push("</ul>");
|
||||
}
|
||||
|
||||
toc.push("<hr>")
|
||||
toc.push("</div>");
|
||||
|
||||
return toc.join("");
|
||||
}
|
||||
|
||||
|
||||
var includeExpr = /^@include\s+([A-Za-z0-9-_]+)(?:\.)?([a-zA-Z]*)$/gmi;
|
||||
// Allow including other pages in the data.
|
||||
function loadIncludes(data, current_file) {
|
||||
return data.replace(includeExpr, function(src, name, ext) {
|
||||
try {
|
||||
var include_path = path.join(current_file, "../", name+"."+(ext || "markdown"))
|
||||
return loadIncludes(fs.readFileSync(include_path, "utf8"), current_file);
|
||||
} catch(e) {
|
||||
return "";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function convertData(data) {
|
||||
// Convert it to HTML from Markdown
|
||||
var html = markdown.toHTML(markdown.parse(data), {xhtml:true})
|
||||
.replace(/<hr><\/hr>/g, "<hr />")
|
||||
.replace(/(\<h[2-6])\>([^<]+)(\<\/h[1-6]\>)/gmi, function(o, ts, c, te) {
|
||||
return ts+' id="'+formatIdString(c)+'">'+c+te;
|
||||
})
|
||||
.replace(/(\<h[2-4][^>]+\>)([^<]+)(\<\/h[2-4]\>)/gmi,
|
||||
function(o, ts, c, te) {
|
||||
var mark = ' <span>' +
|
||||
'<a class="top" href="#">↑</a>' +
|
||||
'<a class="mark" href="#' +
|
||||
formatIdString(c) + '">#</a></span>';
|
||||
|
||||
return ts+c+mark+te;
|
||||
});
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
|
||||
if (argc > 3) {
|
||||
var filename = argv[3],
|
||||
output = template,
|
||||
html;
|
||||
|
||||
fs.readFile(filename, "utf8", function(err, data) {
|
||||
if (err) throw err;
|
||||
|
||||
// go recursion.
|
||||
data = loadIncludes(data, filename);
|
||||
// go markdown.
|
||||
html = convertData(data);
|
||||
filename = path.basename(filename, '.markdown');
|
||||
output = output.replace(/{{filename}}/g, filename);
|
||||
|
||||
if (filename != "_toc" && filename != "index") {
|
||||
if (data) {
|
||||
html = generateToc(data) + "\n" + html;
|
||||
}
|
||||
|
||||
output = output.replace("{{section}}", filename+" - ")
|
||||
} else {
|
||||
if (filename === "index") {
|
||||
html = '<div id="toc">' + html + '</div>';
|
||||
}
|
||||
output = output.replace("{{section}}", "");
|
||||
output = output.replace(/<body([^>]*)>/, '<body class="'+filename+'" $1>');
|
||||
}
|
||||
if (html.length == 0) {
|
||||
html = "Sorry, this section is currently undocumented, \
|
||||
but we'll be working on it.";
|
||||
}
|
||||
output = output.replace("{{content}}", html);
|
||||
|
||||
if (argc > 4) {
|
||||
fs.writeFile(argv[4], output);
|
||||
} else {
|
||||
process.stdout.write(output);
|
||||
}
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user