1. Benchmarks
  2. Download
  3. Build
  4. API
    1. Timers
    2. File System I/O
    3. TCP
      1. Server
      2. Connection
    4. HTTP
      1. Server
        1. Request
        2. Response
      2. Client
        1. Request
        2. Response
    5. Modules

Node

Purely asynchronous I/O for V8 javascript.

This is an example of a web server written with Node which responds with "Hello World" after waiting two seconds:

new node.http.Server(function (req, res) {
  setTimeout(function () {
    res.sendHeader(200, [["Content-Type", "text/plain"]]);
    res.sendBody("Hello World");
    res.finish();
  }, 2000);
}).listen(8000);
puts("Server running at http://127.0.0.1:8000/");

Node is an evented sandbox where users cannot execute blocking I/O. This is already natural for Javascript programmers, as the DOM is almost entirely asynchronous. The goal is to provide an easy way to create efficient network applications.

See the API documentation for more examples.

Node is free to download, use, and build upon.

Benchmarks

TODO

Download

TODO

Build

./configure
make
make install

API

Conventions: Callbacks are object members which are prefixed with on. All methods and members are camel cased. Constructors always have a capital first letter.

Timers

Timers allow one to schedule execution of a function for a later time.

Timers in Node work as they do in the browser: setTimeout(), setInterval(), clearTimeout(), clearInterval(). See Mozilla's documentation for more information.

File System

node.tcp

node.http

Node provides a web server and client interface. The interface is rather low-level but complete (it does not limit you from any of HTTP's features). The interface abstracts the transfer-encoding (i.e. chunked or identity), message boundaries, and persistent connections.

node.http.Server

new node.http.Server(request_handler, options);

Creates a new web server.

The options argument is optional. The options argument accepts the same values as the options argument for node.tcp.Server does.

The request_handler is a callback which is made on each request with a ServerRequest and ServerResponse arguments.

server.listen(port, hostname)

Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections directed to any address.

server.close()

Stops the server from accepting new connections.

node.http.ServerRequest

This object is created internally by a HTTP server—not by the user. It is passed as the first argument to the request_handler callback.

req.method
The request method as a string. Read only. Example: "GET", "DELETE".
req.uri
Request URI. (Object.)
req.uri.anchor
req.uri.query
req.uri.file
req.uri.directory
req.uri.path
req.uri.relative
req.uri.port
req.uri.host
req.uri.password
req.uri.user
req.uri.authority
req.uri.protocol
req.uri.queryKey
req.uri.toString(), req.uri.source
The original URI found in the status line.
req.headers
The request headers expressed as an array of 2-element arrays. Read only. Example:
[ ["Content-Length", "123"]
, ["Content-Type", "text/plain"]
, ["Connection", "keep-alive"]
, ["Accept", "*/*"]
]
req.http_version
The HTTP protocol version as a string. Read only. Examples: "1.1", "1.0"
req.onBody
Callback. Should be set by the user to be informed of when a piece of the message body is received. Example:
req.onBody = function (chunk) {
  puts("part of the body: " + chunk);
};
A chunk of the body is given as the single argument. The transfer-encoding has been removed.

The body chunk is either a String in the case of UTF-8 encoding or an array of numbers in the case of raw encoding. The body encoding is set with req.setBodyEncoding().

req.onBodyComplete
Callback. Made exactly once for each message. No arguments. After onBodyComplete is executed onBody will no longer be called.
req.setBodyEncoding(encoding)
Set the encoding for the request body. Either "utf8" or "raw". Defaults to raw.

node.http.ServerResponse

res.sendHeader(status_code, headers)
Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The second argument, headers, should be an array of 2-element arrays, representing the response headers.

Example:

var body = "hello world";
res.sendHeader(200, [ ["Content-Length", body.length]
                    , ["Content-Type", "text/plain"]
                    ]);
This method must only be called once on a message and it must be called before res.finish() is called.
res.sendBody(chunk)
This method must be called after sendHeader was called. It sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.
res.finish()
This method signals that all of the response headers and body has been sent; that server should consider this message complete. The method, res.finish(), MUST be called on each response.

node.http.Client

An HTTP client is constructed with a server address as its argument, then the user issues one or more requests. Depending on the server connected to, the client might pipeline the requests or reestablish the connection after each connection. (CURRENTLY: The client does not pipeline.)

Example of connecting to google.com

var google = new node.http.Client(80, "google.com");
var req = google.get("/");
req.finish(function (res) {
  puts("STATUS: " + res.status_code);
  puts("HEADERS: " + JSON.stringify(res.headers));
  res.setBodyEncoding("utf8");
  res.onBody = function (chunk) {
    puts("BODY: " + chunk);
  };
});
new node.http.Client(port, host);
Constructs a new HTTP client. port and host refer to the server to be connected to. A connection is not established until a request is issued.
client.get(path, request_headers);
client.head(path, request_headers);
client.post(path, request_headers);
client.del(path, request_headers);
client.put(path, request_headers);
Issues a request. request_headers is optional. request_headers should be an array of 2-element arrays. Additional request headers might be added internally by Node. Returns a ClientRequest object.

Important: the request is not complete. This method only sends the header of the request. One needs to call req.finish() to finalize the request and retrieve the response. (This sounds convoluted but it provides a chance for the user to stream a body to the server with req.sendBody. GET and HEAD requests normally are without bodies but HTTP does not forbid it, so neither do we.)

node.http.ClientRequest

This object created internally and returned from the request methods of a node.http.Client. It represents an in-progress request whose header has already been sent.

req.sendBody(chunk, encoding)
Sends a sucessive peice of the body. By calling this method many times, the user can stream a request body to a server—in that case it is suggested to use the ["Transfer-Encoding", "chunked"] header line when creating the request.

The chunk argument should be an array of integers or a string.

The encoding argument is optional and only applies when chunk is a string. The encoding argument should be either "utf8" or "ascii". By default the body uses ASCII encoding, as it is faster.

TODO

req.finish(response_handler)
Finishes sending the request. If any parts of the body are unsent, it will flush them to the socket. If the request is chunked, this will send the terminating "0\r\n\r\n".

The parameter response_handler is a user-supplied callback which will be executed exactly once when the server response headers have been received. The response_handler callback is executed with one argument: a ClientResponse object.

node.http.ClientResponse

This object is created internally and passed to the response_handler callback (is given to the client in req.finish function). The response object appears exactly as the header is completely received but before any part of the response body has been read.

res.status_code
The 3-digit HTTP response status code. (E.G. 404.)
res.http_version
The HTTP version of the connected-to server. Probably either "1.1" or "1.0".
res.headers
The response headers. An Array of 2-element arrays.
res.onBody
Callback. Should be set by the user to be informed of when a piece of the message body is received. A chunk of the body is given as the single argument. The transfer-encoding has been removed.

The body chunk is either a String in the case of UTF-8 encoding or an array of numbers in the case of raw encoding. The body encoding is set with res.setBodyEncoding().

res.onBodyComplete
Callback. Made exactly once for each message. No arguments. After onBodyComplete is executed onBody will no longer be called.
res.setBodyEncoding(encoding)
Set the encoding for the response body. Either "utf8" or "raw". Defaults to raw.

Modules

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 mjsunit.js.

The contents of foo.js:

include("mjsunit");
function onLoad () {
  assertEquals(1, 2);
}

The contents of mjsunit.js:

function fail (expected, found, name_opt) {
  // ...
}
function deepEquals (a, b) {
  // ...
}
exports.assertEquals = function (expected, found, name_opt) {
  if (!deepEquals(found, expected)) {
    fail(expected, found, name_opt);
  }
};

Here the module mjsunit.js has exported the function assertEquals(). mjsunit.js must be in the same directory as foo.js for include() to find it. The module path is relative to the file calling include(). The module path does not include filename extensions like .js.

include() inserts the exported objects from the specified module into the global namespace.

Because file loading does not happen instantaneously, and because Node has a policy of never blocking, the callback onLoad can be set and will notify the user when all the included modules are loaded. Each file/module can have an onLoad callback.

To export an object, add to the special exports object.

The functions fail and deepEquals are not exported and remain private to the module.

require() is like include() except does not polute the global namespace. It returns a namespace object. The exported objects can only be guaranteed to exist after the onLoad() callback is made. For example:

var mjsunit = require("mjsunit");
function onLoad () {
  mjsunit.assertEquals(1, 2);
}

include() and require() cannot be used after onLoad() is called. So put them at the beginning of your file.