using namespace v8;
extern "C" void
- init (Handle<Object> target)
+ init (Handle<Object> target)
{
HandleScope scope;
- target->Set(String::New("hello"), String::New("World"));
+ target->Set(String::New("hello"), String::New("world"));
}
This source code needs to be built into `hello.node`, the binary Addon. To
### assert.equal(actual, expected, [message])
-Tests shallow, coercive equality with the equal comparison operator ( `==` ).
+Tests shallow, coercive equality with the equal comparison operator ( `==` ).
### assert.notEqual(actual, expected, [message])
### assert.notDeepEqual(actual, expected, [message])
-Tests for any deep inequality.
+Tests for any deep inequality.
### assert.strictEqual(actual, expected, [message])
-Tests strict equality, as determined by the strict equality operator ( `===` )
+Tests strict equality, as determined by the strict equality operator ( `===` )
### assert.notStrictEqual(actual, expected, [message])
-Tests strict non-equality, as determined by the strict not equal operator ( `!==` )
+Tests strict non-equality, as determined by the strict not equal operator ( `!==` )
### assert.throws(block, [error], [message])
console.log(len + " bytes: " + buf.toString('utf8', 0, len));
// 12 bytes: ½ + ¼ = ¾
-
+
### buffer.toString(encoding, start=0, end=buffer.length)
### Buffer.byteLength(string, encoding='utf8')
-Gives the actual byte length of a string. This is not the same as
+Gives the actual byte length of a string. This is not the same as
`String.prototype.length` since that returns the number of *characters* in a
string.
### buffer.length
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
+of the contents. `length` refers to the amount of memory allocated for the
buffer object. It does not change when the contents of the buffer are changed.
buf = new Buffer(1234);
buf1 = new Buffer(26);
buf2 = new Buffer(26);
-
+
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97; // 97 is ASCII a
buf2[i] = 33; // ASCII !
console.log(buf2.toString('ascii', 0, 25));
// !!!!!!!!qrst!!!!!!!!!!!!!
-
+
### buffer.slice(start, end=buffer.length)
exec = require('child_process').exec,
child;
- child = exec('cat *.js bad_file | wc -l',
+ child = exec('cat *.js bad_file | wc -l',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
## dgram
-Datagram sockets are available through `require('dgram')`. Datagrams are most commonly
+Datagram sockets are available through `require('dgram')`. Datagrams are most commonly
handled as IP/UDP messages, but they can also be used over Unix domain sockets.
### Event: 'message'
### dgram.createSocket(type, [callback])
Creates a datagram socket of the specified types. Valid types are:
-`udp4`, `udp6`, and `unix_dgram`.
+`udp4`, `udp6`, and `unix_dgram`.
Takes an optional callback which is added as a listener for `message` events.
For Unix domain datagram sockets, the destination address is a pathname in the filesystem.
An optional callback may be supplied that is invoked after the `sendto` call is completed
-by the OS. It is not safe to re-use `buf` until the callback is invoked. Note that
+by the OS. It is not safe to re-use `buf` until the callback is invoked. Note that
unless the socket is bound to a pathname with `bind()` there is no way to receive messages
on this socket.
### dgram.send(buf, offset, length, port, address, [callback])
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
+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
re-used. Note that DNS lookups will delay the time that a send takes place, at
least until the next tick. The only way to know for sure that a send has taken place
### dgram.close()
-Close the underlying socket and stop listening for data on it. UDP sockets
+Close the underlying socket and stop listening for data on it. UDP sockets
automatically listen for messages, even if they did not call `bind()`.
### dgram.address()
-Returns an object containing the address information for a socket. For UDP sockets,
+Returns an object containing the address information for a socket. For UDP sockets,
this object will contain `address` and `port`. For Unix domain sockets, it will contain
only `address`.
### dgram.setTTL(ttl)
Sets the `IP_TTL` socket option. TTL stands for "Time to Live," but in this context it
-specifies the number of IP hops that a packet is allowed to go through. Each router or
+specifies the number of IP hops that a packet is allowed to go through. Each router or
gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a
-router, it will not be forwarded. Changing TTL values is typically done for network
+router, it will not be forwarded. Changing TTL values is typically done for network
probes or when multicasting.
The argument to `setTTL()` is a number of hops between 1 and 255. The default on most
### 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.
+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)
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.,
+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)
Reverse resolves an ip address to an array of domain names.
-The callback has arguments `(err, domains)`.
+The callback has arguments `(err, domains)`.
If there an an error, `err` will be non-null and an instanceof the Error
object.
## Events
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
+a peer connects to it, a `fs.readStream` emits an event when the file is
opened. All objects which emit events are instances of `events.EventEmitter`.
You can access this module by doing: `require("events");`
-Typically, event names are represented by a camel-cased string, however,
+Typically, event names are represented by a camel-cased string, however,
there aren't any strict restrictions on that, as any string will be accepted.
Functions can be then be attached to objects, to be executed when an event
To access the EventEmitter class, `require('events').EventEmitter`.
-When an `EventEmitter` instance experiences an error, the typical action is
+When an `EventEmitter` instance experiences an error, the typical action is
to emit an `'error'` event. Error events are treated as a special case in node.
-If there is no listener for it, then the default action is to print a stack
+If there is no listener for it, then the default action is to print a stack
trace and exit the program.
All EventEmitters emit the event `'newListener'` when new listeners are
Adds a listener to the end of the listeners array for the specified event.
- server.on('connection', function (stream) {
- console.log('someone connected!');
- });
+ server.on('connection', function (stream) {
+ console.log('someone connected!');
+ });
#### emitter.once(event, listener)
invoked only the first time the event is fired, after which
it is removed.
- server.once('connection', function (stream) {
- console.log('Ah, we have our first user!');
- });
+ server.once('connection', function (stream) {
+ console.log('Ah, we have our first user!');
+ });
#### 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.
- var callback = function(stream) {
- console.log('someone connected!');
- };
- server.on('connection', callback);
- // ...
- server.removeListener('connection', callback);
+ var callback = function(stream) {
+ console.log('someone connected!');
+ };
+ server.on('connection', callback);
+ // ...
+ server.removeListener('connection', callback);
#### emitter.removeAllListeners(event)
Returns an array of listeners for the specified event. This array can be
manipulated, e.g. to remove listeners.
- server.on('connection', function (stream) {
- console.log('someone connected!');
- });
- console.log(util.inspect(server.listeners('connection')); // [ [Function] ]
+ server.on('connection', function (stream) {
+ console.log('someone connected!');
+ });
+ console.log(util.inspect(server.listeners('connection')); // [ [Function] ]
#### emitter.emit(event, [arg1], [arg2], [...])
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
-synchronous forms.
+synchronous forms.
The asynchronous form always take a completion callback as its last argument.
The arguments passed to the completion callback depend on the method, but the
### fs.rename(path1, path2, [callback])
-Asynchronous rename(2). No arguments other than a possible exception are given
+Asynchronous rename(2). No arguments other than a possible exception are given
to the completion callback.
### fs.renameSync(path1, path2)
### fs.truncate(fd, len, [callback])
-Asynchronous ftruncate(2). No arguments other than a possible exception are
+Asynchronous ftruncate(2). No arguments other than a possible exception are
given to the completion callback.
### fs.truncateSync(fd, len)
### fs.chmod(path, mode, [callback])
-Asynchronous chmod(2). No arguments other than a possible exception are given
+Asynchronous chmod(2). No arguments other than a possible exception are given
to the completion callback.
### fs.chmodSync(path, mode)
Synchronous chmod(2).
-
+
### fs.stat(path, [callback])
-Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
+Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
`stats` is a `fs.Stats` object. It looks like this:
{ dev: 2049,
### 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
+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])
-Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where
+Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where
`stats` is a `fs.Stats` object.
### fs.statSync(path)
### fs.link(srcpath, dstpath, [callback])
-Asynchronous link(2). No arguments other than a possible exception are given to
+Asynchronous link(2). No arguments other than a possible exception are given to
the completion callback.
### fs.linkSync(dstpath, srcpath)
### fs.symlink(linkdata, path, [callback])
-Asynchronous symlink(2). No arguments other than a possible exception are given
+Asynchronous symlink(2). No arguments other than a possible exception are given
to the completion callback.
### fs.symlinkSync(linkdata, path)
### fs.readlink(path, [callback])
-Asynchronous readlink(2). The callback gets two arguments `(err,
-resolvedPath)`.
+Asynchronous readlink(2). The callback gets two arguments `(err,
+resolvedPath)`.
### fs.readlinkSync(path)
### fs.realpath(path, [callback])
-Asynchronous realpath(2). The callback gets two arguments `(err,
+Asynchronous realpath(2). The callback gets two arguments `(err,
resolvedPath)`.
### fs.realpathSync(path)
### fs.unlink(path, [callback])
-Asynchronous unlink(2). No arguments other than a possible exception are given
+Asynchronous unlink(2). No arguments other than a possible exception are given
to the completion callback.
### fs.unlinkSync(path)
### fs.rmdir(path, [callback])
-Asynchronous rmdir(2). No arguments other than a possible exception are given
+Asynchronous rmdir(2). No arguments other than a possible exception are given
to the completion callback.
### fs.rmdirSync(path)
### fs.mkdir(path, mode, [callback])
-Asynchronous mkdir(2). No arguments other than a possible exception are given
+Asynchronous mkdir(2). No arguments other than a possible exception are given
to the completion callback.
### fs.mkdirSync(path, mode)
### fs.close(fd, [callback])
-Asynchronous close(2). No arguments other than a possible exception are given
+Asynchronous close(2). No arguments other than a possible exception are given
to the completion callback.
### fs.closeSync(fd)
### fs.open(path, flags, mode=0666, [callback])
Asynchronous file open. See open(2). Flags can be 'r', 'r+', 'w', 'w+', 'a',
-or 'a+'. The callback gets two arguments `(err, fd)`.
+or 'a+'. The callback gets two arguments `(err, fd)`.
### fs.openSync(path, flags, mode=0666)
-Synchronous open(2).
+Synchronous open(2).
### fs.write(fd, buffer, offset, length, position, [callback])
### fs.writeSync(fd, buffer, offset, length, position)
-Synchronous version of buffer-based `fs.write()`. Returns the number of bytes
+Synchronous version of buffer-based `fs.write()`. Returns the number of bytes
written.
### fs.writeSync(fd, str, position, encoding='utf8')
-Synchronous version of string-based `fs.write()`. Returns the number of bytes
+Synchronous version of string-based `fs.write()`. Returns the number of bytes
written.
### fs.read(fd, buffer, offset, length, position, [callback])
### fs.readSync(fd, buffer, offset, length, position)
-Synchronous version of buffer-based `fs.read`. Returns the number of
+Synchronous version of buffer-based `fs.read`. Returns the number of
`bytesRead`.
### fs.readSync(fd, length, position, encoding)
-Synchronous version of string-based `fs.read`. Returns the number of
+Synchronous version of string-based `fs.read`. Returns the number of
`bytesRead`.
### fs.readFile(filename, [encoding], [callback])
console.log('the previous mtime was: ' + prev.mtime);
});
-These stat objects are instances of `fs.Stat`.
+These stat objects are instances of `fs.Stat`.
### fs.unwatchFile(filename)
`function (errno) { }`
- Emitted when the server closes.
+ Emitted when the server closes.
### Event: 'request'
### response.addTrailers(headers)
This method adds HTTP trailing headers (a header but at the end of the
-message) to the response.
+message) to the response.
-Trailers will **only** be emitted if chunked encoding is used for the
+Trailers will **only** be emitted if chunked encoding is used for the
response; if it is not (e.g., if the request was HTTP/1.0), they will
be silently discarded.
* Sending a 'Content-length' header will disable the default chunked encoding.
-* Sending an 'Expect' header will immediately send the request headers.
+* Sending an 'Expect' header will immediately send the request headers.
Usually, when sending 'Expect: 100-continue', you should both set a timeout
and listen for the `continue` event. See RFC2616 Section 8.2.3 for more
information.
Example:
var util = require('util');
-
+
It is possible to extend node with other modules. See `'Modules'`
## Modules
Without the leading `'./'`, like `require('assert')` the module is searched
for in the `require.paths` array. `require.paths` on my system looks like
-this:
+this:
`[ '/home/ryan/.node_modules' ]`
## 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
+methods for creating both servers and clients (called streams). You can include
this module with `require("net");`
### net.createServer(connectionListener)
Example:
- path.normalizeArray(['',
+ path.normalizeArray(['',
'foo', 'bar', 'baz', 'asdf', 'quux', '..'])
// returns
[ '', 'foo', 'bar', 'baz', 'asdf' ]
the first character, then it returns an empty string. Examples:
path.extname('index.html')
- // returns
+ // returns
'.html'
path.extname('index')
### process.exit(code=0)
-Ends the process with the specified `code`. If omitted, exit uses the
+Ends the process with the specified `code`. If omitted, exit uses the
'success' code `0`.
To exit with a 'failure' code:
### process.getuid()
-Gets the user identity of the process. (See getuid(2).)
+Gets the user identity of the process. (See getuid(2).)
This is the numerical userid, not the username.
console.log('Current uid: ' + process.getuid());
mjr:~$ node
Type '.help' for options.
- node> a = [ 1, 2, 3];
+ > a = [ 1, 2, 3];
[ 1, 2, 3 ]
- node> a.forEach(function (v) {
+ > a.forEach(function (v) {
... console.log(v);
... });
1
alias node="env NODE_NO_READLINE=1 rlwrap node"
-### repl.start(prompt='node> ', stream=process.openStdin())
+### repl.start(prompt='> ', stream=process.openStdin())
Starts a REPL with `prompt` as the prompt and `stream` for all I/O. `prompt`
-is optional and defaults to `node> `. `stream` is optional and defaults to
+is optional and defaults to `> `. `stream` is optional and defaults to
`process.openStdin()`.
Multiple REPLs may be started against the same running instance of node. Each
for connecting to TCP sockets, and `socat` can be used to connect to both Unix and
TCP sockets.
-By starting a REPL from a Unix socket-based server instead of stdin, you can
+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.
The special variable `_` (underscore) contains the result of the last expression.
- node> [ "a", "b", "c" ]
+ > [ "a", "b", "c" ]
[ 'a', 'b', 'c' ]
- node> _.length
+ > _.length
3
- node> _ += 1
+ > _ += 1
4
-The REPL provides access to any variables in the global scope. You can expose a variable
+The REPL provides access to any variables in the global scope. You can expose a variable
to the REPL explicitly by assigning it to the `context` object associated with each
`REPLServer`. For example:
Things in the `context` object appear as local within the REPL:
- mjr:~$ node repl_test.js
- node> m
+ mjr:~$ node repl_test.js
+ > m
'message'
There are a few special REPL commands:
`'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'`
-* `href`: The full URL that was originally parsed.
-
+* `href`: The full URL that was originally parsed.
+
Example: `'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'`
* `protocol`: The request protocol.
-
+
Example: `'http:'`
-* `host`: The full host portion of the URL, including port and authentication information.
-
+* `host`: The full host portion of the URL, including port and authentication information.
+
Example: `'user:pass@host.com:8080'`
* `auth`: The authentication information portion of a URL.
-
+
Example: `'user:pass'`
* `hostname`: Just the hostname portion of the host.