From bf0d278a4501b03e74d9e02309d667af2182c2a3 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Sat, 3 Oct 2009 22:42:03 +0200 Subject: [PATCH] Improve "make dist" remove generated doc from repo. --- .gitignore | 3 + Makefile | 26 +- doc/api.html | 2146 -------------------------------------------- doc/api.xml | 2260 ----------------------------------------------- doc/common.xsl | 61 ++ doc/manpage.xsl | 28 + doc/node.1 | 2044 ------------------------------------------ wscript | 25 +- 8 files changed, 124 insertions(+), 6469 deletions(-) delete mode 100644 doc/api.html delete mode 100644 doc/api.xml create mode 100644 doc/common.xsl create mode 100644 doc/manpage.xsl delete mode 100644 doc/node.1 diff --git a/.gitignore b/.gitignore index b9360130ef..bd85513b42 100644 --- a/.gitignore +++ b/.gitignore @@ -3,5 +3,8 @@ build tags .lock-wscript *.pyc +doc/api.xml +doc/api.html +doc/node.1 node node_g diff --git a/Makefile b/Makefile index 7e8c3be696..db159f0bb0 100644 --- a/Makefile +++ b/Makefile @@ -14,10 +14,10 @@ install: uninstall: @tools/waf-light uninstall - + test: all python tools/test.py --mode=release - + test-all: all python tools/test.py --mode=debug,release @@ -40,26 +40,34 @@ doc/api.xml: doc/api.txt asciidoc -b docbook -d manpage -o doc/api.xml doc/api.txt doc/node.1: doc/api.xml - xsltproc --output doc/node.1 \ - --nonet /etc/asciidoc/docbook-xsl/manpage.xsl \ - doc/api.xml + xsltproc --output doc/node.1 --nonet doc/manpage.xsl doc/api.xml website-upload: doc scp doc/* linode:~/tinyclouds/node/ clean: + @-rm doc/node.1 doc/api.xml doc/api.html @tools/waf-light clean distclean: @tools/waf-light distclean - @-rm -rf _build_ - @-rm -f Makefile @-rm -f *.pyc check: @tools/waf-light check -dist: - @tools/waf-light dist +VERSION=$(shell git-describe) +TARNAME=node-$(VERSION) + +dist: doc/node.1 doc/api.html + git-archive --prefix=$(TARNAME)/ HEAD > $(TARNAME).tar + mkdir -p $(TARNAME)/doc + cp doc/node.1 $(TARNAME)/doc/node.1 + cp doc/api.html $(TARNAME)/doc/api.html + tar rf $(TARNAME).tar \ + $(TARNAME)/doc/node.1 \ + $(TARNAME)/doc/api.html + rm -r $(TARNAME) + gzip -f -9 $(TARNAME).tar .PHONY: benchmark clean dist distclean check uninstall install all test test-all website-upload diff --git a/doc/api.html b/doc/api.html deleted file mode 100644 index 4c51750430..0000000000 --- a/doc/api.html +++ /dev/null @@ -1,2146 +0,0 @@ - - - - - -NODE(1) - - - - - - - -

NAME

-
-

node - evented I/O for V8 javascript

-
-

SYNOPSIS

-
-

An example of a web server written with Node which responds with "Hello -World":

-
-
-
include("/utils.js");
-include("/http.js");
-createServer(function (request, response) {
-  response.sendHeader(200, {"Content-Type": "text/plain"});
-  response.sendBody("Hello World\n");
-  response.finish();
-}).listen(8000);
-puts("Server running at http://127.0.0.1:8000/");
-
-

To run the server, put the code into a file called example.js and execute -it with the node program

-
-
-
> node example.js
-Server running at http://127.0.0.1:8000/
-
-
-

API

-
-

Node supports 3 string encodings. UTF-8 ("utf8"), ASCII ("ascii"), and -Binary ("binary"). "ascii" and "binary" only look at the first 8 bits -of the 16bit javascript string characters. Both are relatively fast—use -them if you can. "utf8" is slower and should be avoided when possible.

-

Unless otherwise noted, functions are all asynchronous and do not block -execution.

-

Helpers

-

These objects are available to all programs.

-
-
-node.cwd() -
-
-

-Returns the current working directory of the process. -

-
-
-node.compile(source, scriptOrigin) -
-
-

-Just like eval() except that you can specify a scriptOrigin for better -error reporting. -

-
-
-__filename -
-
-

-The filename of the script being executed. -

-
-
-require(path) -
-
-include(path) -
-
-

-See the modules section. -

-
-
-node.libraryPaths -
-
-

-The search path for absolute path arguments to require() and include(). -

-
-
-

The process Object

-

process is the equivalent of window in browser-side javascript. It is -the global scope. process is an instance of node.EventEmitter.

-
- ---- - - - - - - - - - - - - - -
Event Parameters Notes

"exit"

code

Made when the process exits. - A listener on this event should not try to perform - I/O since the process will forcibly exit in less - than microsecond. However, it is a good hook to - perform constant time checks of the module’s - state (like for unit tests). -
- The parameter code is the integer exit code - passed to process.exit().

-
-
-
-process.exit(code=0) -
-
-

-Ends the process with the specified code. By default it exits with the -success code 0. -

-
-
-process.ARGV -
-
-

-An array containing the command line arguments. -

-
-
-process.ENV -
-
-

-An object containing the user environment. See environ(7). -

-
-
-

Utilities

-

These function are in "/utils.js". Use require("/utils.js") to access them.

-
-
-puts(string) -
-
-

-Outputs the string and a trailing new-line to stdout. -

-
-
-print(string) -
-
-

-Like puts() but without the trailing new-line. -

-
-
-debug(string) -
-
-

-A synchronous output function. Will block the process and -output the string immediately to stdout. -

-
-
-inspect(object) -
-
-

-Return a string representation of the object. (For debugging.) -

-
-
-exec(command) -
-
-

-Executes the command as a child process, buffers the output and returns it -in a promise callback. -

-
-
-
include("/utils.js");
-exec("ls /").addCallback(function (stdout, stderr) {
-  puts(stdout);
-});
-
-
    -
  • -

    -on success: stdout buffer, stderr buffer -

    -
  • -
  • -

    -on error: exit code, stdout buffer, stderr buffer -

    -
  • -
-
-
-

Events

-

Many objects in Node emit events: a TCP server emits an event each time -there is a connection, a child process emits an event when it exits. All -objects which emit events are are instances of node.EventEmitter.

-

Events are represented by a camel-cased string. Here are some examples: -"connection", "receive", "messageBegin".

-

Functions can be then be attached to objects, to be executed when an event -is emitted. These functions are called listeners.

-

Some asynchronous file operations return an EventEmitter called a -promise. A promise emits just a single event when the operation is -complete.

-

node.EventEmitter

-

All EventEmitters emit the event "newListener" when new listeners are -added.

-
- ---- - - - - - - - - - - - - - -
Event Parameters Notes

"newListener"

event, listener

This event is made - any time someone adds - a new listener.

-
-
-
-emitter.addListener(event, listener) -
-
-

-Adds a listener to the end of the listeners array for the specified event. -

-
-
-
server.addListener("connection", function (socket) {
-  puts("someone connected!");
-});
-
-
-
-emitter.listeners(event) -
-
-

-Returns an array of listeners for the specified event. This array can be -manipulated, e.g. to remove listeners. -

-
-
-emitter.emit(event, arg1, arg2, …) -
-
-

-Execute each of the listeners in order with the supplied arguments. -

-
-
-

node.Promise

-

node.Promise inherits from node.eventEmitter. A promise emits one of two -events: "success" or "error". After emitting its event, it will not -emit anymore events.

-
- ---- - - - - - - - - - - - - - - - - - - -
Event Parameters Notes

"success"

(depends)

"error"

(depends)

-
-
-
-promise.addCallback(listener) -
-
-

-Adds a listener for the "success" event. Returns the same promise object. -

-
-
-promise.addErrback(listener) -
-
-

-Adds a listener for the "error" event. Returns the same promise object. -

-
-
-promise.emitSuccess(arg1, arg2, …) -
-
-

-If you created the promise (by doing new node.Promise()) then call -emitSuccess to emit the "success" event with the given arguments. -

-

(promise.emit("success", arg1, arg2, …) should also work, but doesn’t at -the moment due to a bug; use emitSuccess instead.)

-
-
-promise.emitError(arg1, arg2, …) -
-
-

-Emits the "error" event. -

-
-
-promise.wait() -
-
-

-Blocks futher execution until the promise emits a success or error event. -Events setup before the call to promise.wait() was made may still be -emitted and executed while promise.wait() is blocking. -

-

If there was a single argument to the "success" event then it is returned. -If there were multiple arguments to "success" then they are returned as an -array.

-

If "error" was emitted instead, wait() throws an error.

-

IMPORTANT promise.wait() is not a true fiber/coroutine. If any other -promises are created and made to wait while the first promise waits, the -first promise’s wait will not return until all others return. The benefit of -this is a simple implementation and the event loop does not get blocked. -Disadvantage is the possibility of situations where the promise stack grows -infinitely large because promises keep getting created and keep being told -to wait(). Use promise.wait() sparingly—probably best used only during -program setup, not during busy server activity.

-
-
-

Standard I/O

-

Standard I/O is handled through a special object node.stdio. stdout and -stdin are fully non-blocking (even when piping to files). stderr is -synchronous.

-
- ---- - - - - - - - - - - - - - - - - - - -
Event Parameters Notes

"data"

data

Made when stdin has received a chunk of data. - Depending on the encoding that stdin was opened - with, data will be a string. This event will - only be emited after node.stdio.open() has - been called.

"close"

Made when stdin has been closed.

-
-
-
-node.stdio.open(encoding="utf8") -
-
-

-Open stdin. The program will not exit until node.stdio.close() has been -called or the "close" event has been emitted. -

-
-
-node.stdio.write(data) -
-
-

-Write data to stdout. -

-
-
-node.stdio.writeError(data) -
-
-

-Write data to stderr. Synchronous. -

-
-
-node.stdio.close() -
-
-

-Close stdin. -

-
-
-

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

-

The contents of foo.js:

-
-
-
var circle = require("circle.js");
-include("/utils.js");
-puts("The area of a circle of radius 4 is " + circle.area(4));
-
-

The contents of circle.js:

-
-
-
var PI = 3.14;
-
-exports.area = function (r) {
-  return PI * r * r;
-};
-
-exports.circumference = function (r) {
-  return 2 * PI * r;
-};
-
-

The module circle.js has exported the functions area() and -circumference(). To export an object, add to the special exports -object. (Alternatively, one can use this instead of exports.) Variables -local to the module will be private. In this example the variable PI is -private to circle.js. The function puts() comes from the module -"/utils.js". Because include("/utils.js") was called, puts() is in the -global namespace.

-

The module path is relative to the file calling require(). That is, -circle.js must be in the same directory as foo.js for require() to -find it.

-

Like require() the function include() also loads a module. Instead of -returning a namespace object, include() will add the module’s exports into -the global namespace. For example:

-
-
-
include("circle.js");
-include("/utils.js");
-puts("The area of a cirlce of radius 4 is " + area(4));
-
-

When an absolute path is given to require() or include(), like -require("/mjsunit.js") the module is searched for in the -node.libraryPaths array. node.libraryPaths on my system looks like this:

-
-
-
[ "/home/ryan/.node_libraries"
-, "/home/ryan/local/node/lib/node_libraries"
-, "/"
-]
-
-

That is, first Node looks for "/home/ryan/.node_libraries/mjsunit.js" and -then for "/home/ryan/local/node/lib/node_libraries/mjsunit.js". If not -found, it finally looks for "/mjsunit.js" (in the root directory).

-

node.libraryPaths can be modified at runtime by simply unshifting new -paths on to it and at startup with the NODE_LIBRARY_PATHS environmental -variable (which should be a list of paths, colon separated).

-

Node comes with several libraries which are installed when "make install" -is run. These are currently undocumented, but do look them up in your -system.

-

Timers

-
-
-setTimeout(callback, delay) -
-
-

-To schedule execution of callback after delay milliseconds. Returns a -timeoutId for possible use with clearTimeout(). -

-
-
-clearTimeout(timeoutId) -
-
-

-Prevents said timeout from triggering. -

-
-
-setInterval(callback, delay) -
-
-

-To schedule the repeated execution of callback every delay milliseconds. Returns -a intervalId for possible use with clearInterval(). -

-
-
-clearInterval(intervalId) -
-
-

-Stops a interval from triggering. -

-
-
-

Child Processes

-

Node provides a tridirectional popen(3) facility through the class -node.ChildProcess. It is possible to stream data through the child’s stdin, -stdout, and stderr in a fully non-blocking way.

-

node.ChildProcess

-
- ---- - - - - - - - - - - - - - - - - - - - - - - - -
Event Parameters Notes

"output"

data

Each time the child process - sends data to its stdout, this event is - emitted. data is a string. + If the child - process closes its stdout stream (a common - thing to do on exit), this event will be emitted - with data === null.

"error"

data

Identical to the "output" event except for - stderr instead of stdout.

"exit"

code

This event is emitted after the child process - ends. code is the final exit code of the - process. One can be assured that after this - event is emitted that the "output" and - "error" callbacks will no longer be made.

-
-
-
-node.createChildProcess(command) -
-
-

-Launches a new process with the given command. For example: -

-
-
-
var ls = node.createChildProcess("ls -lh /usr");
-ls.addListener("output", function (data) {
-  puts(data);
-});
-
-
-
-child.pid -
-
-

-The PID of the child process. -

-
-
-child.write(data, encoding="ascii") -
-
-

-Write data to the child process’s stdin. The second argument is optional and -specifies the encoding: possible values are "utf8", "ascii", and -"binary". -

-
-
-child.close() -
-
-

-Closes the process’s stdin stream. -

-
-
-child.kill(signal=node.SIGTERM) -
-
-

-Send a single to the child process. If no argument is given, the process -will be sent node.SIGTERM. The standard POSIX signals are defined under -the node namespace (node.SIGINT, node.SIGUSR1, …). -

-
-
-

File I/O

-

File I/O is provided by simple wrappers around standard POSIX functions. -All POSIX wrappers have a similar form. -They return a promise (node.Promise). Example:

-
-
-
var promise = node.fs.unlink("/tmp/hello");
-promise.addCallback(function () {
-  puts("successfully deleted /tmp/hello");
-});
-
-

There is no guaranteed ordering to the POSIX wrappers. The -following is very much prone to error

-
-
-
node.fs.rename("/tmp/hello", "/tmp/world");
-node.fs.stat("/tmp/world").addCallback(function (stats) {
-  puts("stats: " + JSON.stringify(stats));
-});
-
-

It could be that stat() is executed before the rename(). -The correct way to do this is to chain the promises.

-
-
-
node.fs.rename("/tmp/hello", "/tmp/world").addCallback(function () {
-  node.fs.stat("/tmp/world").addCallback(function (stats) {
-    puts("stats: " + JSON.stringify(stats));
-  });
-});
-
-

Or use the promise.wait() functionality:

-
-
-
node.fs.rename("/tmp/hello", "/tmp/world").wait();
-node.fs.stat("/tmp/world").addCallback(function (stats) {
-  puts("stats: " + JSON.stringify(stats));
-});
-
-
-
-node.fs.rename(path1, path2) -
-
-

- See rename(2). -

-
    -
  • -

    -on success: no parameters. -

    -
  • -
  • -

    -on error: no parameters. -

    -
  • -
-
-
-node.fs.stat(path) -
-
-

- See stat(2). -

-
    -
  • -

    -on success: Returns node.fs.Stats object. It looks like this: - { dev: 2049, ino: 305352, mode: 16877, nlink: 12, uid: 1000, gid: 1000, - rdev: 0, size: 4096, blksize: 4096, blocks: 8, atime: - "2009-06-29T11:11:55Z", mtime: "2009-06-29T11:11:40Z", ctime: - "2009-06-29T11:11:40Z" } - See the node.fs.Stats section below for more information. -

    -
  • -
  • -

    -on error: no parameters. -

    -
  • -
-
-
-node.fs.unlink(path) -
-
-

- See unlink(2) -

-
    -
  • -

    -on success: no parameters. -

    -
  • -
  • -

    -on error: no parameters. -

    -
  • -
-
-
-node.fs.rmdir(path) -
-
-

- See rmdir(2) -

-
    -
  • -

    -on success: no parameters. -

    -
  • -
  • -

    -on error: no parameters. -

    -
  • -
-
-
-node.fs.mkdir(path, mode) -
-
-

- See mkdir(2) -

-
    -
  • -

    -on success: no parameters. -

    -
  • -
  • -

    -on error: no parameters. -

    -
  • -
-
-
-node.fs.readdir(path) -
-
-

- Reads the contents of a directory. -

-
    -
  • -

    -on success: One argument, an array containing the names (strings) of the - files in the directory (excluding "." and ".."). -

    -
  • -
  • -

    -on error: no parameters. -

    -
  • -
-
-
-node.fs.close(fd) -
-
-

- See close(2) -

-
    -
  • -

    -on success: no parameters. -

    -
  • -
  • -

    -on error: no parameters. -

    -
  • -
-
-
-node.fs.open(path, flags, mode) -
-
-

- See open(2). The constants like O_CREAT are defined at node.O_CREAT. -

-
    -
  • -

    -on success: fd is given as the parameter. -

    -
  • -
  • -

    -on error: no parameters. -

    -
  • -
-
-
-node.fs.write(fd, data, position, encoding) -
-
-

- Write data to the file specified by fd. position refers to the offset - from the beginning of the file where this data should be written. If - position is null, the data will be written at the current position. - See pwrite(2). -

-
    -
  • -

    -on success: returns an integer written which specifies how many bytes were written. -

    -
  • -
  • -

    -on error: no parameters. -

    -
  • -
-
-
-node.fs.read(fd, length, position, encoding) -
-
-

-Read data from the file specified by fd. -

-

length is an integer specifying the number of -bytes to read.

-

position is an integer specifying where to begin -reading from in the file.

-
    -
  • -

    -on success: returns data, bytes_read, what was read from the file. -

    -
  • -
  • -

    -on error: no parameters. -

    -
  • -
-
-
-node.fs.cat(filename, encoding="utf8") -
-
-

-Outputs the entire contents of a file. Example: -

-
-
-
node.fs.cat("/etc/passwd").addCallback(function (content) {
-  puts(content);
-});
-
-
    -
  • -

    -on success: returns data, what was read from the file. -

    -
  • -
  • -

    -on error: no parameters. -

    -
  • -
-
-
-

node.fs.Stats

-

Objects returned from node.fs.stat() are of this type.

-
-
-stats.isFile() -
-
-stats.isDirectory() -
-
-stats.isBlockDevice() -
-
-stats.isCharacterDevice() -
-
-stats.isSymbolicLink() -
-
-stats.isFIFO() -
-
-stats.isSocket() -
-
-

-… -

-
-
-

HTTP

-

To use the HTTP server and client one must require("/http.js") or -include("/http.js").

-

The HTTP interfaces in Node are designed to support many features -of the protocol which have been traditionally difficult to use. -In particular, large, possibly chunk-encoded, messages. The interface is -careful to never buffer entire requests or responses—the -user is able to stream data.

-

HTTP message headers are represented by an object like this

-
-
-
{ "Content-Length": "123"
-, "Content-Type": "text/plain"
-, "Connection": "keep-alive"
-, "Accept": "*/*"
-}
-
-

In order to support the full spectrum of possible HTTP applications, Node’s -HTTP API is very low-level. It deals with connection handling and message -parsing only. It parses a message into headers and body but it does not -parse the actual headers or the body.

-

http.Server

-
- ---- - - - - - - - - - - - - - - - - - - - - - - - -
Event Parameters Notes

"request"

request, response

request is an instance of http.ServerRequest -
- response is an instance of http.ServerResponse

"connection"

connection

When a new TCP connection is established. - connection is an object of type - http.Connection. Usually users - will not want to access this event. - The connection can also be - accessed at request.connection.

"close"

errorno

Emitted when the server closes. errorno - is an integer which indicates what, if any, - error caused the server to close. If no - error occured errorno will be 0.

-
-
-
-http.createServer(request_listener, options); -
-
-

-Returns a new web server object. -

-

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

-

The request_listener is a function which is automatically -added to the "request" event.

-
-
-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. This function is synchronous. -

-
-
-server.close() -
-
-

-Stops the server from accepting new connections. -

-
-
-

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.

-
- ---- - - - - - - - - - - - - - - - - - - -
Event Parameters Notes

"body"

chunk

Emitted when a piece of the - message body is received. Example: A chunk - of the body is given as the single - argument. The transfer-encoding has been - decoded. The body chunk is a String. The - body encoding is set with - request.setBodyEncoding().

"complete"

(none)

Emitted exactly once for each message. - No arguments. After emitted no other - events will be emitted on the request.

-
-
-
-request.method -
-
-

-The request method as a string. Read only. Example: -"GET", "DELETE". -

-
-
-request.uri -
-
-

-Request URI Object. This contains only the parameters that are -present in the actual HTTP request. That is, if the request is -

-
-
-
GET /status?name=ryan HTTP/1.1\r\n
-Accept: text/plain\r\n
-\r\n
-
-

Then request.uri will be

-
-
-
{ path: "/status",
-  file: "status",
-  directory: "/",
-  params: { "name" : "ryan" }
-}
-
-

In particular, note that request.uri.protocol is -undefined. This is because there was no URI protocol given -in the actual HTTP Request.

-

Here is what’s available: request.uri.anchor, request.uri.query, -request.uri.file, request.uri.directory, request.uri.path, -request.uri.relative, request.uri.port, request.uri.host, -request.uri.password, request.uri.user, request.uri.authority, -request.uri.protocol, request.uri.params, request.uri.toString(), -request.uri.source

-
-
-request.headers -
-
-

-Read only. -

-
-
-request.httpVersion -
-
-

-The HTTP protocol version as a string. Read only. Examples: -"1.1", "1.0" -

-
-
-request.setBodyEncoding(encoding) -
-
-

-Set the encoding for the request body. Either "utf8" or "binary". Defaults -to "binary". -

-
-
-request.pause() -
-
-

-Pauses request from emitting events. Useful to throttle back an upload. -

-
-
-request.resume() -
-
-

-Resumes a paused request. -

-
-
-request.connection -
-
-

-The http.Connection object. -

-
-
-

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.

-
-
-response.sendHeader(statusCode, headers) -
-
-

-Sends a response header to the request. The status code is a 3-digit HTTP -status code, like 404. The second argument, headers are the response headers. -

-

Example:

-
-
-
var body = "hello world";
-response.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 response.finish() is called.

-
-
-response.sendBody(chunk, encoding="ascii") -
-
-

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

-

If chunk is a string, the second parameter -specifies how to encode it into a byte stream. By default the -encoding is "ascii".

-

Note: This is the raw HTTP body and has nothing to do with -higher-level multi-part body encodings that may be used.

-

The first time sendBody is called, it will send the buffered header -information and the first body to the client. The second time -sendBody is called, Node assumes you’re going to be streaming data, and -sends that seperately. That is, the response is buffered up to the -first chunk of body.

-
-
-response.finish() -
-
-

-This method signals to the server that all of the response headers and body -has been sent; that server should consider this message complete. -The method, response.finish(), MUST be called on each -response. -

-
-
-

http.Client

-

An HTTP client is constructed with a server address as its -argument, the returned handle is then used to issue 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 implementation does not pipeline requests.

-

Example of connecting to google.com

-
-
-
var google = http.createClient(80, "google.com");
-var request = google.get("/");
-request.finish(function (response) {
-  puts("STATUS: " + response.statusCode);
-  puts("HEADERS: " + JSON.stringify(response.headers));
-  response.setBodyEncoding("utf8");
-  response.addListener("body", function (chunk) {
-    puts("BODY: " + chunk);
-  });
-});
-
-
-
-http.createClient(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; if necessary establishes connection. Returns a http.ClientRequest instance. -

-

request_headers is optional. -Additional request headers might be added internally -by Node. Returns a ClientRequest object.

-

Do remember to include the Content-Length header if you -plan on sending a body. If you plan on streaming the body, perhaps -set Transfer-Encoding: chunked.

-
- - - -
-
Note
-
the request is not complete. This method only sends -the header of the request. One needs to call -request.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 -request.sendBody().)
-
-
-
-

http.ClientRequest

-

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

-
- ---- - - - - - - - - - - - - - -
Event Parameters Notes

"response"

response

Emitted when a response is received to this request. Typically the user will -set a listener to this via the request.finish() method.
-This event is emitted only once.
-The response argument will be an instance of http.ClientResponse.

-
-
-
-request.sendBody(chunk, encoding="ascii") -
-
-

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

-

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.

-
-
-request.finish(responseListener) -
-
-

-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 responseListener is a callback which -will be executed when the response headers have been received. -The responseListener callback is executed with one -argument which is an instance of http.ClientResponse.

-

In the responseListener callback, one can add more listeners to the -response, in particular listening for the "body" event. Note that -the responseListener is called before any part of the body is receieved, -so there is no need to worry about racing to catch the first part of the -body. As long as a listener for "body" is added during the -responseListener callback, the entire body will be caught.

-
-
-
// Good
-request.finish(function (response) {
-  response.addListener("body", function (chunk) {
-    puts("BODY: " + chunk);
-  });
-});
-
-// Bad - misses all or part of the body
-request.finish(function (response) {
-  setTimeout(function () {
-    response.addListener("body", function (chunk) {
-      puts("BODY: " + chunk);
-    });
-  }, 10);
-});
-
-
-
-

http.ClientResponse

-

This object is created internally and passed to the "response" event.

-
- ---- - - - - - - - - - - - - - - - - - - -
Event Parameters Notes

"body"

chunk

Emitted when a piece of the message body is received. Example: A chunk of -the body is given as the single argument. The transfer-encoding has been -decoded. The body chunk a String. The body encoding is set with -response.setBodyEncoding().

"complete"

Emitted exactly once for each message. No arguments. -After emitted no other events will be emitted on the response.

-
-
-
-response.statusCode -
-
-

- The 3-digit HTTP response status code. E.G. 404. -

-
-
-response.httpVersion -
-
-

- The HTTP version of the connected-to server. Probably either - "1.1" or "1.0". -

-
-
-response.headers -
-
-

- The response headers. -

-
-
-response.setBodyEncoding(encoding) -
-
-

- Set the encoding for the response body. Either "utf8" or "binary". - Defaults to "binary". -

-
-
-response.pause() -
-
-

- Pauses response from emitting events. Useful to throttle back a download. -

-
-
-response.resume() -
-
-

- Resumes a paused response. -

-
-
-response.client -
-
-

- A reference to the http.Client that this response belongs to. -

-
-
-

Multipart Parsing

-

A library to parse HTTP requests with multipart/form-data is included with -Node. To use it, require("/multipart.js").

-
-
-multipart.parse(options) -
-
-
    -
  • -

    -on success: Returns an object where each key holds the value of one part of - the stream. options can either be an instance of - http.ServerRequest or an object containing a boundary and a - data key. -

    -
  • -
  • -

    -on error: no parameters. -

    -
  • -
-
-
-

multipart.Stream

-

Here is an example for parsing a multipart/form-data request:

-
-
-
var multipart = require('/multipart.js');
-var stream = new multipart.Stream(options);
-var parts = {};
-
-stream.addListener('part', function (part) {
-  var name = part.headers['Content-Disposition'].name;
-  var buffer = '';
-
-  part.addListener('body', function(chunk) {
-    buffer = buffer + chunk;
-  });
-
-  part.addListener('complete', function() {
-    parts[name] = buffer;
-  });
-});
-
-stream.addListener('complete', function() {
-  // The parts object now contains all parts and data
-});
-
-
- ---- - - - - - - - - - - - - - - - - - - -
Event Parameters Notes

"part"

part

Emitted when a new part is found in the stream. - part is an instance of multipart.Part.

"complete"

Emitted when the end of the stream is reached.

-
-

multipart.Part

-
- ---- - - - - - - - - - - - - - - - - - - -
Event Parameters Notes

"body"

chunk

Emitted when a chunk of body is read.

"complete"

Emitted when the end of the part is reached.

-
-

TCP

-

To use the TCP server and client one must require("/tcp.js") or -include("/tcp.js").

-

tcp.Server

-

Here is an example of a echo server which listens for connections -on port 7000

-
-
-
include("/tcp.js");
-var server = createServer(function (socket) {
-  socket.setEncoding("utf8");
-  socket.addListener("connect", function () {
-    socket.send("hello\r\n");
-  });
-  socket.addListener("receive", function (data) {
-    socket.send(data);
-  });
-  socket.addListener("eof", function () {
-    socket.send("goodbye\r\n");
-    socket.close();
-  });
-});
-server.listen(7000, "localhost");
-
-
- ---- - - - - - - - - - - - - - - - - - - -
Event Parameters Notes

"connection"

connection

Emitted when a new connection is made. - connection is an instance of tcp.Connection.

"close"

errorno

Emitted when the server closes. errorno - is an integer which indicates what, if any, - error caused the server to close. If no - error occurred errorno will be 0.

-
-
-
-tcp.createServer(connection_listener); -
-
-

-Creates a new TCP server. -

-

The connection_listener argument is automatically set as a listener for -the "connection" event.

-
-
-server.listen(port, host=null, backlog=128) -
-
-

-Tells the server to listen for TCP connections to port and host. -

-

host is optional. If host is not specified the server will accept client -connections on any network address.

-

The third argument, backlog, is also optional and defaults to 128. The -backlog argument defines the maximum length to which the queue of pending -connections for the server may grow.

-

This function is synchronous.

-
-
-server.close() -
-
-

-Stops the server from accepting new connections. This function is -asynchronous, the server is finally closed when the server emits a "close" -event. -

-
-
-

tcp.Connection

-

This object is used as a TCP client and also as a server-side -socket for tcp.Server.

-
- ---- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Event Parameters Notes

"connect"

Call once the connection is established - after a call to createConnection() or - connect().

"receive"

data

Called when data is received on the - connection. data will be a string. - Encoding of data is set by - connection.setEncoding().

"eof"

Called when the other end of the - connection sends a FIN packet. - After this is emitted the readyState - will be "writeOnly". One should probably - just call connection.close() when this - event is emitted.

"timeout"

Emitted if the connection times out from - inactivity. The "close" event will be - emitted immediately following this event.

"close"

had_error

Emitted once the connection is fully - closed. The argument had_error - is a boolean which says if the connection - was closed due to a transmission error. - (TODO: access error codes.)

-
-
-
-tcp.createConnection(port, host="127.0.0.1") -
-
-

-Creates a new connection object and opens a connection to the specified -port and host. If the second parameter is omitted, localhost is assumed. -

-

When the connection is established the "connect" event will be emitted.

-
-
-connection.connect(port, host="127.0.0.1") -
-
-

-Opens a connection to the specified port and host. createConnection() -also opens a connection; normally this method is not needed. Use this only -if a connection is closed and you want to reuse the object to connect to -another server. -

-

This function is asynchronous. When the "connect" event is emitted the -connection is established. If there is a problem connecting, the "connect" -event will not be emitted, the "close" event will be emitted with -had_error == true.

-
-
-connection.remoteAddress -
-
-

-The string representation of the remote IP address. For example, -"74.125.127.100" or "2001:4860:a005::68". -

-

This member is only present in server-side connections.

-
-
-connection.readyState -
-
-

-Either "closed", "open", "opening", "readOnly", or "writeOnly". -

-
-
-connection.setEncoding(encoding) -
-
-

-Sets the encoding (either "ascii", "utf8", or "binary") for data that is received. -

-
-
-connection.send(data, encoding="ascii") -
-
-

-Sends data on the connection. The second parameter specifies the encoding -in the case of a string—it defaults to ASCII because encoding to UTF8 is -rather slow. -

-
-
-connection.close() -
-
-

-Half-closes the connection. I.E., it sends a FIN packet. It is -possible the server will still send some data. After calling -this readyState will be "readOnly". -

-
-
-connection.forceClose() -
-
-

-Ensures that no more I/O activity happens on this socket. Only -necessary in case of errors (parse error or so). -

-
-
-connection.readPause() -
-
-

-Pauses the reading of data. That is, "receive" events will not be emitted. -Useful to throttle back an upload. -

-
-
-connection.readResume() -
-
-

-Resumes reading if reading was paused by readPause(). -

-
-
-connection.setTimeout(timeout) -
-
-

-Sets the connection to timeout after timeout milliseconds of inactivity on -the connection. By default all tcp.Connection objects have a timeout -of 60 seconds (60000 ms). -

-

If timeout is 0, then the idle timeout is disabled.

-
-
-connection.setNoDelay(noDelay=true) -
-
-

-Disables the Nagle algorithm. By default TCP connections use the Nagle -algorithm, they buffer data before sending it off. Setting noDelay will -immediately fire off data each time connection.send() is called. -

-
-
-

DNS

-

Here is an example of which resolves "www.google.com" then reverse -resolves the IP addresses which are returned.

-
-
-
var resolution = node.dns.resolve4("www.google.com");
-
-resolution.addCallback(function (addresses, ttl, cname) {
-  puts("addresses: " + JSON.stringify(addresses));
-  puts("ttl: " + JSON.stringify(ttl));
-  puts("cname: " + JSON.stringify(cname));
-
-  for (var i = 0; i < addresses.length; i++) {
-    var a = addresses[i];
-    var reversing = node.dns.reverse(a);
-    reversing.addCallback( function (domains, ttl, cname) {
-      puts("reverse for " + a + ": " + JSON.stringify(domains));
-    });
-    reversing.addErrback( function (code, msg) {
-      puts("reverse for " + a + " failed: " + msg);
-    });
-  }
-});
-
-resolution.addErrback(function (code, msg) {
-  puts("error: " + msg);
-});
-
-
-
-node.dns.resolve4(domain) -
-
-

-Resolves a domain (e.g. "google.com") into an array of IPv4 addresses (e.g. -["74.125.79.104", "74.125.79.105", "74.125.79.106"]). -This function returns a promise. -

-
    -
  • -

    -on success: returns addresses, ttl, cname. ttl (time-to-live) is an integer - specifying the number of seconds this result is valid for. cname is the - canonical name for the query. -

    -
  • -
  • -

    -on error: returns code, msg. code is one of the error codes listed - below and msg is a string describing the error in English. -

    -
  • -
-
-
-node.dns.resolve6(domain) -
-
-

-The same as node.dns.resolve4() except for IPv6 queries (an AAAA query). -

-
-
-node.dns.reverse(ip) -
-
-

-Reverse resolves an ip address to an array of domain names. -

-
    -
  • -

    -on success: returns domains, ttl, cname. ttl (time-to-live) is an integer - specifying the number of seconds this result is valid for. cname is the - canonical name for the query. domains is an array of domains. -

    -
  • -
  • -

    -on error: returns code, msg. code is one of the error codes listed - below and msg is a string describing the error in English. -

    -
  • -
-
-
-

Each DNS query can return an error code.

-
    -
  • -

    -node.dns.TEMPFAIL: timeout, SERVFAIL or similar. -

    -
  • -
  • -

    -node.dns.PROTOCOL: got garbled reply. -

    -
  • -
  • -

    -node.dns.NXDOMAIN: domain does not exists. -

    -
  • -
  • -

    -node.dns.NODATA: domain exists but no data of reqd type. -

    -
  • -
  • -

    -node.dns.NOMEM: out of memory while processing. -

    -
  • -
  • -

    -node.dns.BADQUERY: the query is malformed. -

    -
  • -
-
-

REPL

-
-

A Read-Eval-Print-Loop is available both as a standalone program and easily -includable in other programs.

-

The standalone REPL is called node-repl and is installed at -$PREFIX/bin/node-repl. It’s recommended to use it with the program -rlwrap for a better user interface. I set

-
-
-
alias node-repl="rlwrap node-repl"
-
-

in my zsh configuration.

-

Inside the REPL, Control+D will exit. The special variable _ (underscore) contains the -result of the last expression.

-

The library is called /repl.js and it can be used like this:

-
-
-
include("/utils.js");
-include("/tcp.js");
-nconnections = 0;
-createServer(function (c) {
-  error("Connection!");
-  nconnections += 1;
-  c.close();
-}).listen(5000);
-require("/repl.js").start("simple tcp server> ");
-
-
-

Extension API

-
-

External modules can be compiled and dynamically linked into Node. -Node is more or less glue between several C and C++ libraries:

-
    -
  • -

    -V8 Javascript, a C++ library. Used for interfacing with Javascript: - creating objects, calling functions, etc. Documented mostly in the - v8.h header file (deps/v8/include/v8.h in the Node source tree). -

    -
  • -
  • -

    -libev, C event loop library. Anytime one needs to wait for a file - descriptor to become readable, wait for a timer, or wait for a signal to - received one will need to interface with libev. That is, if you perform - any I/O, libev will need to be used. Node uses the EV_DEFAULT event - loop. Documentation can be found here. -

    -
  • -
  • -

    -libeio, C thread pool library. Used to execute blocking POSIX system - calls asynchronously. Mostly wrappers already exist for such calls, in - src/file.cc so you will probably not need to use it. If you do need it, - look at the header file deps/libeio/eio.h. -

    -
  • -
  • -

    -Internal Node libraries. Most importantly is the node::EventEmitter - class which you will likely want to derive from. -

    -
  • -
  • -

    -Others. Look in deps/ for what else is available. -

    -
  • -
-

Node statically compiles all its dependencies into the executable. When -compiling your module, you don’t need to worry about linking to any of these -libraries.

-

Here is a sample Makefile taken from -node_postgres:

-
-
-
binding.node: binding.o Makefile
-        gcc -shared -o binding.node  binding.o \
-                -L`pg_config --libdir` -lpq
-
-binding.o: binding.cc Makefile
-        gcc `node --cflags` -I`pg_config --includedir` \
-                binding.cc -c -o binding.o
-
-clean:
-        rm -f binding.o binding.node
-.PHONY: clean
-
-

As you can see, the only thing your module needs to know about Node is the -CFLAGS that node was compiled with which are gotten from node --cflags -If you want to make a debug build, then use node_g --cflags. (node_g is -the debug build of node, which can built with configure --debug; make; make -install.)

-

Node extension modules are dynamically linked libraries with a .node -extension. Node opens this file and looks for a function called init() -which must be of the form:

-
-
-
extern "C" void init (Handle<Object> target)
-
-

In this function you can create new javascript objects and attach them to -target. Here is a very simple module:

-
-
-
extern "C" void
-init (Handle<Object> target)
-{
-  HandleScope scope;
-  target->Set(String::New("hello"), String::New("World"));
-}
-
-

Further documentation will come soon. For now see the source code of -node_postgres.

-
- - - diff --git a/doc/api.xml b/doc/api.xml deleted file mode 100644 index 8a542c3943..0000000000 --- a/doc/api.xml +++ /dev/null @@ -1,2260 +0,0 @@ - - - - -node -1 - - - node - evented I/O for V8 javascript - - -An example of a web server written with Node which responds with "Hello -World": -include("/utils.js"); -include("/http.js"); -createServer(function (request, response) { - response.sendHeader(200, {"Content-Type": "text/plain"}); - response.sendBody("Hello World\n"); - response.finish(); -}).listen(8000); -puts("Server running at http://127.0.0.1:8000/"); -To run the server, put the code into a file called example.js and execute -it with the node program -> node example.js -Server running at http://127.0.0.1:8000/ - - -API -Node supports 3 string encodings. UTF-8 ("utf8"), ASCII ("ascii"), and -Binary ("binary"). "ascii" and "binary" only look at the first 8 bits -of the 16bit javascript string characters. Both are relatively fast—use -them if you can. "utf8" is slower and should be avoided when possible. -Unless otherwise noted, functions are all asynchronous and do not block -execution. - -Helpers -These objects are available to all programs. - - - -node.cwd() - - - -Returns the current working directory of the process. - - - - - -node.compile(source, scriptOrigin) - - - -Just like eval() except that you can specify a scriptOrigin for better -error reporting. - - - - - -__filename - - - -The filename of the script being executed. - - - - - -require(path) - - -include(path) - - - -See the modules section. - - - - - -node.libraryPaths - - - -The search path for absolute path arguments to require() and include(). - - - - - - -The <literal>process</literal> Object -process is the equivalent of window in browser-side javascript. It is -the global scope. process is an instance of node.EventEmitter. - - - - - - - - Event - Parameters - Notes - - - - -"exit" -code -Made when the process exits. - A listener on this event should not try to perform - I/O since the process will forcibly exit in less - than microsecond. However, it is a good hook to - perform constant time checks of the module’s - state (like for unit tests). - - The parameter code is the integer exit code - passed to process.exit(). - - - - - - - -process.exit(code=0) - - - -Ends the process with the specified code. By default it exits with the -success code 0. - - - - - -process.ARGV - - - -An array containing the command line arguments. - - - - - -process.ENV - - - -An object containing the user environment. See environ(7). - - - - - - -Utilities -These function are in "/utils.js". Use require("/utils.js") to access them. - - - -puts(string) - - - -Outputs the string and a trailing new-line to stdout. - - - - - -print(string) - - - -Like puts() but without the trailing new-line. - - - - - -debug(string) - - - -A synchronous output function. Will block the process and -output the string immediately to stdout. - - - - - -inspect(object) - - - -Return a string representation of the object. (For debugging.) - - - - - -exec(command) - - - -Executes the command as a child process, buffers the output and returns it -in a promise callback. - -include("/utils.js"); -exec("ls /").addCallback(function (stdout, stderr) { - puts(stdout); -}); - - - -on success: stdout buffer, stderr buffer - - - - -on error: exit code, stdout buffer, stderr buffer - - - - - - - - -Events -Many objects in Node emit events: a TCP server emits an event each time -there is a connection, a child process emits an event when it exits. All -objects which emit events are are instances of node.EventEmitter. -Events are represented by a camel-cased string. Here are some examples: -"connection", "receive", "messageBegin". -Functions can be then be attached to objects, to be executed when an event -is emitted. These functions are called listeners. -Some asynchronous file operations return an EventEmitter called a -promise. A promise emits just a single event when the operation is -complete. - -<literal>node.EventEmitter</literal> -All EventEmitters emit the event "newListener" when new listeners are -added. - - - - - - - - Event - Parameters - Notes - - - - -"newListener" -event, listener -This event is made - any time someone adds - a new listener. - - - - - - - -emitter.addListener(event, listener) - - - -Adds a listener to the end of the listeners array for the specified event. - -server.addListener("connection", function (socket) { - puts("someone connected!"); -}); - - - - -emitter.listeners(event) - - - -Returns an array of listeners for the specified event. This array can be -manipulated, e.g. to remove listeners. - - - - - -emitter.emit(event, arg1, arg2, …) - - - -Execute each of the listeners in order with the supplied arguments. - - - - - - -<literal>node.Promise</literal> -node.Promise inherits from node.eventEmitter. A promise emits one of two -events: "success" or "error". After emitting its event, it will not -emit anymore events. - - - - - - - - Event - Parameters - Notes - - - - -"success" -(depends) - - - -"error" -(depends) - - - - - - - - -promise.addCallback(listener) - - - -Adds a listener for the "success" event. Returns the same promise object. - - - - - -promise.addErrback(listener) - - - -Adds a listener for the "error" event. Returns the same promise object. - - - - - -promise.emitSuccess(arg1, arg2, …) - - - -If you created the promise (by doing new node.Promise()) then call -emitSuccess to emit the "success" event with the given arguments. - -(promise.emit("success", arg1, arg2, …) should also work, but doesn’t at -the moment due to a bug; use emitSuccess instead.) - - - - -promise.emitError(arg1, arg2, …) - - - -Emits the "error" event. - - - - - -promise.wait() - - - -Blocks futher execution until the promise emits a success or error event. -Events setup before the call to promise.wait() was made may still be -emitted and executed while promise.wait() is blocking. - -If there was a single argument to the "success" event then it is returned. -If there were multiple arguments to "success" then they are returned as an -array. -If "error" was emitted instead, wait() throws an error. -IMPORTANT promise.wait() is not a true fiber/coroutine. If any other -promises are created and made to wait while the first promise waits, the -first promise’s wait will not return until all others return. The benefit of -this is a simple implementation and the event loop does not get blocked. -Disadvantage is the possibility of situations where the promise stack grows -infinitely large because promises keep getting created and keep being told -to wait(). Use promise.wait() sparingly—probably best used only during -program setup, not during busy server activity. - - - - - - -Standard I/O -Standard I/O is handled through a special object node.stdio. stdout and -stdin are fully non-blocking (even when piping to files). stderr is -synchronous. - - - - - - - - Event - Parameters - Notes - - - - -"data" -data -Made when stdin has received a chunk of data. - Depending on the encoding that stdin was opened - with, data will be a string. This event will - only be emited after node.stdio.open() has - been called. - - -"close" - -Made when stdin has been closed. - - - - - - - -node.stdio.open(encoding="utf8") - - - -Open stdin. The program will not exit until node.stdio.close() has been -called or the "close" event has been emitted. - - - - - -node.stdio.write(data) - - - -Write data to stdout. - - - - - -node.stdio.writeError(data) - - - -Write data to stderr. Synchronous. - - - - - -node.stdio.close() - - - -Close stdin. - - - - - - -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 -circle.js. -The contents of foo.js: -var circle = require("circle.js"); -include("/utils.js"); -puts("The area of a circle of radius 4 is " + circle.area(4)); -The contents of circle.js: -var PI = 3.14; - -exports.area = function (r) { - return PI * r * r; -}; - -exports.circumference = function (r) { - return 2 * PI * r; -}; -The module circle.js has exported the functions area() and -circumference(). To export an object, add to the special exports -object. (Alternatively, one can use this instead of exports.) Variables -local to the module will be private. In this example the variable PI is -private to circle.js. The function puts() comes from the module -"/utils.js". Because include("/utils.js") was called, puts() is in the -global namespace. -The module path is relative to the file calling require(). That is, -circle.js must be in the same directory as foo.js for require() to -find it. -Like require() the function include() also loads a module. Instead of -returning a namespace object, include() will add the module’s exports into -the global namespace. For example: -include("circle.js"); -include("/utils.js"); -puts("The area of a cirlce of radius 4 is " + area(4)); -When an absolute path is given to require() or include(), like -require("/mjsunit.js") the module is searched for in the -node.libraryPaths array. node.libraryPaths on my system looks like this: -[ "/home/ryan/.node_libraries" -, "/home/ryan/local/node/lib/node_libraries" -, "/" -] -That is, first Node looks for "/home/ryan/.node_libraries/mjsunit.js" and -then for "/home/ryan/local/node/lib/node_libraries/mjsunit.js". If not -found, it finally looks for "/mjsunit.js" (in the root directory). -node.libraryPaths can be modified at runtime by simply unshifting new -paths on to it and at startup with the NODE_LIBRARY_PATHS environmental -variable (which should be a list of paths, colon separated). -Node comes with several libraries which are installed when "make install" -is run. These are currently undocumented, but do look them up in your -system. - - -Timers - - - -setTimeout(callback, delay) - - - -To schedule execution of callback after delay milliseconds. Returns a -timeoutId for possible use with clearTimeout(). - - - - - -clearTimeout(timeoutId) - - - -Prevents said timeout from triggering. - - - - - -setInterval(callback, delay) - - - -To schedule the repeated execution of callback every delay milliseconds. Returns -a intervalId for possible use with clearInterval(). - - - - - -clearInterval(intervalId) - - - -Stops a interval from triggering. - - - - - - -Child Processes -Node provides a tridirectional popen(3) facility through the class -node.ChildProcess. It is possible to stream data through the child’s stdin, -stdout, and stderr in a fully non-blocking way. - -<literal>node.ChildProcess</literal> - - - - - - - - Event - Parameters -Notes - - - - -"output" -data -Each time the child process - sends data to its stdout, this event is - emitted. data is a string. + If the child - process closes its stdout stream (a common - thing to do on exit), this event will be emitted - with data === null. - - -"error" -data -Identical to the "output" event except for - stderr instead of stdout. - - -"exit" -code -This event is emitted after the child process - ends. code is the final exit code of the - process. One can be assured that after this - event is emitted that the "output" and - "error" callbacks will no longer be made. - - - - - - - -node.createChildProcess(command) - - - -Launches a new process with the given command. For example: - -var ls = node.createChildProcess("ls -lh /usr"); -ls.addListener("output", function (data) { - puts(data); -}); - - - - -child.pid - - - -The PID of the child process. - - - - - -child.write(data, encoding="ascii") - - - -Write data to the child process’s stdin. The second argument is optional and -specifies the encoding: possible values are "utf8", "ascii", and -"binary". - - - - - -child.close() - - - -Closes the process’s stdin stream. - - - - - -child.kill(signal=node.SIGTERM) - - - -Send a single to the child process. If no argument is given, the process -will be sent node.SIGTERM. The standard POSIX signals are defined under -the node namespace (node.SIGINT, node.SIGUSR1, …). - - - - - - - -File I/O -File I/O is provided by simple wrappers around standard POSIX functions. -All POSIX wrappers have a similar form. -They return a promise (node.Promise). Example: -var promise = node.fs.unlink("/tmp/hello"); -promise.addCallback(function () { - puts("successfully deleted /tmp/hello"); -}); -There is no guaranteed ordering to the POSIX wrappers. The -following is very much prone to error -node.fs.rename("/tmp/hello", "/tmp/world"); -node.fs.stat("/tmp/world").addCallback(function (stats) { - puts("stats: " + JSON.stringify(stats)); -}); -It could be that stat() is executed before the rename(). -The correct way to do this is to chain the promises. -node.fs.rename("/tmp/hello", "/tmp/world").addCallback(function () { - node.fs.stat("/tmp/world").addCallback(function (stats) { - puts("stats: " + JSON.stringify(stats)); - }); -}); -Or use the promise.wait() functionality: -node.fs.rename("/tmp/hello", "/tmp/world").wait(); -node.fs.stat("/tmp/world").addCallback(function (stats) { - puts("stats: " + JSON.stringify(stats)); -}); - - - -node.fs.rename(path1, path2) - - - - See rename(2). - - - - -on success: no parameters. - - - - -on error: no parameters. - - - - - - - -node.fs.stat(path) - - - - See stat(2). - - - - -on success: Returns node.fs.Stats object. It looks like this: - { dev: 2049, ino: 305352, mode: 16877, nlink: 12, uid: 1000, gid: 1000, - rdev: 0, size: 4096, blksize: 4096, blocks: 8, atime: - "2009-06-29T11:11:55Z", mtime: "2009-06-29T11:11:40Z", ctime: - "2009-06-29T11:11:40Z" } - See the node.fs.Stats section below for more information. - - - - -on error: no parameters. - - - - - - - -node.fs.unlink(path) - - - - See unlink(2) - - - - -on success: no parameters. - - - - -on error: no parameters. - - - - - - - -node.fs.rmdir(path) - - - - See rmdir(2) - - - - -on success: no parameters. - - - - -on error: no parameters. - - - - - - - -node.fs.mkdir(path, mode) - - - - See mkdir(2) - - - - -on success: no parameters. - - - - -on error: no parameters. - - - - - - - -node.fs.readdir(path) - - - - Reads the contents of a directory. - - - - -on success: One argument, an array containing the names (strings) of the - files in the directory (excluding "." and ".."). - - - - -on error: no parameters. - - - - - - - -node.fs.close(fd) - - - - See close(2) - - - - -on success: no parameters. - - - - -on error: no parameters. - - - - - - - -node.fs.open(path, flags, mode) - - - - See open(2). The constants like O_CREAT are defined at node.O_CREAT. - - - - -on success: fd is given as the parameter. - - - - -on error: no parameters. - - - - - - - -node.fs.write(fd, data, position, encoding) - - - - Write data to the file specified by fd. position refers to the offset - from the beginning of the file where this data should be written. If - position is null, the data will be written at the current position. - See pwrite(2). - - - - -on success: returns an integer written which specifies how many bytes were written. - - - - -on error: no parameters. - - - - - - - -node.fs.read(fd, length, position, encoding) - - - -Read data from the file specified by fd. - -length is an integer specifying the number of -bytes to read. -position is an integer specifying where to begin -reading from in the file. - - - -on success: returns data, bytes_read, what was read from the file. - - - - -on error: no parameters. - - - - - - - -node.fs.cat(filename, encoding="utf8") - - - -Outputs the entire contents of a file. Example: - -node.fs.cat("/etc/passwd").addCallback(function (content) { - puts(content); -}); - - - -on success: returns data, what was read from the file. - - - - -on error: no parameters. - - - - - - - -<literal>node.fs.Stats</literal> -Objects returned from node.fs.stat() are of this type. - - - -stats.isFile() - - -stats.isDirectory() - - -stats.isBlockDevice() - - -stats.isCharacterDevice() - - -stats.isSymbolicLink() - - -stats.isFIFO() - - -stats.isSocket() - - - -… - - - - - - - -HTTP -To use the HTTP server and client one must require("/http.js") or -include("/http.js"). -The HTTP interfaces in Node are designed to support many features -of the protocol which have been traditionally difficult to use. -In particular, large, possibly chunk-encoded, messages. The interface is -careful to never buffer entire requests or responses—the -user is able to stream data. -HTTP message headers are represented by an object like this -{ "Content-Length": "123" -, "Content-Type": "text/plain" -, "Connection": "keep-alive" -, "Accept": "*/*" -} -In order to support the full spectrum of possible HTTP applications, Node’s -HTTP API is very low-level. It deals with connection handling and message -parsing only. It parses a message into headers and body but it does not -parse the actual headers or the body. - -<literal>http.Server</literal> - - - - - - - -Event - Parameters - Notes - - - - -"request" -request, response -request is an instance of http.ServerRequest - - response is an instance of http.ServerResponse - - -"connection" -connection -When a new TCP connection is established. - connection is an object of type - http.Connection. Usually users - will not want to access this event. - The connection can also be - accessed at request.connection. - - -"close" -errorno -Emitted when the server closes. errorno - is an integer which indicates what, if any, - error caused the server to close. If no - error occured errorno will be 0. - - - - - - - -http.createServer(request_listener, options); - - - -Returns a new web server object. - -The options argument is optional. The -options argument accepts the same values as the -options argument for tcp.Server does. -The request_listener is a function which is automatically -added to the "request" event. - - - - -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. This function is synchronous. - - - - - -server.close() - - - -Stops the server from accepting new connections. - - - - - - -<literal>http.ServerRequest</literal> -This object is created internally by a HTTP server—not by -the user—and passed as the first argument to a "request" listener. - - - - - - - -Event - Parameters - Notes - - - - -"body" -chunk -Emitted when a piece of the - message body is received. Example: A chunk - of the body is given as the single - argument. The transfer-encoding has been - decoded. The body chunk is a String. The - body encoding is set with - request.setBodyEncoding(). - - -"complete" -(none) -Emitted exactly once for each message. - No arguments. After emitted no other - events will be emitted on the request. - - - - - - - -request.method - - - -The request method as a string. Read only. Example: -"GET", "DELETE". - - - - - -request.uri - - - -Request URI Object. This contains only the parameters that are -present in the actual HTTP request. That is, if the request is - -GET /status?name=ryan HTTP/1.1\r\n -Accept: text/plain\r\n -\r\n -Then request.uri will be -{ path: "/status", - file: "status", - directory: "/", - params: { "name" : "ryan" } -} -In particular, note that request.uri.protocol is -undefined. This is because there was no URI protocol given -in the actual HTTP Request. -Here is what’s available: request.uri.anchor, request.uri.query, -request.uri.file, request.uri.directory, request.uri.path, -request.uri.relative, request.uri.port, request.uri.host, -request.uri.password, request.uri.user, request.uri.authority, -request.uri.protocol, request.uri.params, request.uri.toString(), -request.uri.source - - - - -request.headers - - - -Read only. - - - - - -request.httpVersion - - - -The HTTP protocol version as a string. Read only. Examples: -"1.1", "1.0" - - - - - -request.setBodyEncoding(encoding) - - - -Set the encoding for the request body. Either "utf8" or "binary". Defaults -to "binary". - - - - - -request.pause() - - - -Pauses request from emitting events. Useful to throttle back an upload. - - - - - -request.resume() - - - -Resumes a paused request. - - - - - -request.connection - - - -The http.Connection object. - - - - - - -<literal>http.ServerResponse</literal> -This object is created internally by a HTTP server—not by the user. It is -passed as the second parameter to the "request" event. - - - -response.sendHeader(statusCode, headers) - - - -Sends a response header to the request. The status code is a 3-digit HTTP -status code, like 404. The second argument, headers are the response headers. - -Example: -var body = "hello world"; -response.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 response.finish() is called. - - - - -response.sendBody(chunk, encoding="ascii") - - - -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. - -If chunk is a string, the second parameter -specifies how to encode it into a byte stream. By default the -encoding is "ascii". -Note: This is the raw HTTP body and has nothing to do with -higher-level multi-part body encodings that may be used. -The first time sendBody is called, it will send the buffered header -information and the first body to the client. The second time -sendBody is called, Node assumes you’re going to be streaming data, and -sends that seperately. That is, the response is buffered up to the -first chunk of body. - - - - -response.finish() - - - -This method signals to the server that all of the response headers and body -has been sent; that server should consider this message complete. -The method, response.finish(), MUST be called on each -response. - - - - - - -<literal>http.Client</literal> -An HTTP client is constructed with a server address as its -argument, the returned handle is then used to issue 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 implementation does not pipeline requests. -Example of connecting to google.com -var google = http.createClient(80, "google.com"); -var request = google.get("/"); -request.finish(function (response) { - puts("STATUS: " + response.statusCode); - puts("HEADERS: " + JSON.stringify(response.headers)); - response.setBodyEncoding("utf8"); - response.addListener("body", function (chunk) { - puts("BODY: " + chunk); - }); -}); - - - -http.createClient(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; if necessary establishes connection. Returns a http.ClientRequest instance. - -request_headers is optional. -Additional request headers might be added internally -by Node. Returns a ClientRequest object. -Do remember to include the Content-Length header if you -plan on sending a body. If you plan on streaming the body, perhaps -set Transfer-Encoding: chunked. -the request is not complete. This method only sends -the header of the request. One needs to call -request.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 -request.sendBody().) - - - - - -<literal>http.ClientRequest</literal> -This object is created internally and returned from the request methods of a -http.Client. It represents an in-progress request whose header has -already been sent. - - - - - - - -Event - Parameters - Notes - - - - -"response" -response -Emitted when a response is received to this request. Typically the user will -set a listener to this via the request.finish() method. -This event is emitted only once. -The response argument will be an instance of http.ClientResponse. - - - - - - - -request.sendBody(chunk, encoding="ascii") - - - -Sends a chunk of the body. By calling this method -many times, the user can stream a request body to a -server—in that case it is suggested to use the -["Transfer-Encoding", "chunked"] header line when -creating the request. - -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. - - - - -request.finish(responseListener) - - - -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 responseListener is a callback which -will be executed when the response headers have been received. -The responseListener callback is executed with one -argument which is an instance of http.ClientResponse. -In the responseListener callback, one can add more listeners to the -response, in particular listening for the "body" event. Note that -the responseListener is called before any part of the body is receieved, -so there is no need to worry about racing to catch the first part of the -body. As long as a listener for "body" is added during the -responseListener callback, the entire body will be caught. -// Good -request.finish(function (response) { - response.addListener("body", function (chunk) { - puts("BODY: " + chunk); - }); -}); - -// Bad - misses all or part of the body -request.finish(function (response) { - setTimeout(function () { - response.addListener("body", function (chunk) { - puts("BODY: " + chunk); - }); - }, 10); -}); - - - - - -<literal>http.ClientResponse</literal> -This object is created internally and passed to the "response" event. - - - - - - - -Event - Parameters - Notes - - - - -"body" -chunk -Emitted when a piece of the message body is received. Example: A chunk of -the body is given as the single argument. The transfer-encoding has been -decoded. The body chunk a String. The body encoding is set with -response.setBodyEncoding(). - - -"complete" - -Emitted exactly once for each message. No arguments. -After emitted no other events will be emitted on the response. - - - - - - - -response.statusCode - - - - The 3-digit HTTP response status code. E.G. 404. - - - - - -response.httpVersion - - - - The HTTP version of the connected-to server. Probably either - "1.1" or "1.0". - - - - - -response.headers - - - - The response headers. - - - - - -response.setBodyEncoding(encoding) - - - - Set the encoding for the response body. Either "utf8" or "binary". - Defaults to "binary". - - - - - -response.pause() - - - - Pauses response from emitting events. Useful to throttle back a download. - - - - - -response.resume() - - - - Resumes a paused response. - - - - - -response.client - - - - A reference to the http.Client that this response belongs to. - - - - - - - -Multipart Parsing -A library to parse HTTP requests with multipart/form-data is included with -Node. To use it, require("/multipart.js"). - - - -multipart.parse(options) - - - - - -on success: Returns an object where each key holds the value of one part of - the stream. options can either be an instance of - http.ServerRequest or an object containing a boundary and a - data key. - - - - -on error: no parameters. - - - - - - - -<literal>multipart.Stream</literal> -Here is an example for parsing a multipart/form-data request: -var multipart = require('/multipart.js'); -var stream = new multipart.Stream(options); -var parts = {}; - -stream.addListener('part', function (part) { - var name = part.headers['Content-Disposition'].name; - var buffer = ''; - - part.addListener('body', function(chunk) { - buffer = buffer + chunk; - }); - - part.addListener('complete', function() { - parts[name] = buffer; - }); -}); - -stream.addListener('complete', function() { - // The parts object now contains all parts and data -}); - - - - - - - -Event - Parameters - Notes - - - - -"part" -part -Emitted when a new part is found in the stream. - part is an instance of multipart.Part. - - -"complete" - -Emitted when the end of the stream is reached. - - - - - - -<literal>multipart.Part</literal> - - - - - - - -Event - Parameters - Notes - - - - -"body" -chunk -Emitted when a chunk of body is read. - - -"complete" - -Emitted when the end of the part is reached. - - - - - - - -TCP -To use the TCP server and client one must require("/tcp.js") or -include("/tcp.js"). - -<literal>tcp.Server</literal> -Here is an example of a echo server which listens for connections -on port 7000 -include("/tcp.js"); -var server = createServer(function (socket) { - socket.setEncoding("utf8"); - socket.addListener("connect", function () { - socket.send("hello\r\n"); - }); - socket.addListener("receive", function (data) { - socket.send(data); - }); - socket.addListener("eof", function () { - socket.send("goodbye\r\n"); - socket.close(); - }); -}); -server.listen(7000, "localhost"); - - - - - - - -Event - Parameters - Notes - - - - -"connection" -connection -Emitted when a new connection is made. - connection is an instance of tcp.Connection. - - -"close" -errorno -Emitted when the server closes. errorno - is an integer which indicates what, if any, - error caused the server to close. If no - error occurred errorno will be 0. - - - - - - - -tcp.createServer(connection_listener); - - - -Creates a new TCP server. - -The connection_listener argument is automatically set as a listener for -the "connection" event. - - - - -server.listen(port, host=null, backlog=128) - - - -Tells the server to listen for TCP connections to port and host. - -host is optional. If host is not specified the server will accept client -connections on any network address. -The third argument, backlog, is also optional and defaults to 128. The -backlog argument defines the maximum length to which the queue of pending -connections for the server may grow. -This function is synchronous. - - - - -server.close() - - - -Stops the server from accepting new connections. This function is -asynchronous, the server is finally closed when the server emits a "close" -event. - - - - - - -<literal>tcp.Connection</literal> -This object is used as a TCP client and also as a server-side -socket for tcp.Server. - - - - - - - -Event - Parameters - Notes - - - - -"connect" - -Call once the connection is established - after a call to createConnection() or - connect(). - - -"receive" -data -Called when data is received on the - connection. data will be a string. - Encoding of data is set by - connection.setEncoding(). - - -"eof" - -Called when the other end of the - connection sends a FIN packet. - After this is emitted the readyState - will be "writeOnly". One should probably - just call connection.close() when this - event is emitted. - - -"timeout" - -Emitted if the connection times out from - inactivity. The "close" event will be - emitted immediately following this event. - - -"close" -had_error -Emitted once the connection is fully - closed. The argument had_error - is a boolean which says if the connection - was closed due to a transmission error. - (TODO: access error codes.) - - - - - - - -tcp.createConnection(port, host="127.0.0.1") - - - -Creates a new connection object and opens a connection to the specified -port and host. If the second parameter is omitted, localhost is assumed. - -When the connection is established the "connect" event will be emitted. - - - - -connection.connect(port, host="127.0.0.1") - - - -Opens a connection to the specified port and host. createConnection() -also opens a connection; normally this method is not needed. Use this only -if a connection is closed and you want to reuse the object to connect to -another server. - -This function is asynchronous. When the "connect" event is emitted the -connection is established. If there is a problem connecting, the "connect" -event will not be emitted, the "close" event will be emitted with -had_error == true. - - - - -connection.remoteAddress - - - -The string representation of the remote IP address. For example, -"74.125.127.100" or "2001:4860:a005::68". - -This member is only present in server-side connections. - - - - -connection.readyState - - - -Either "closed", "open", "opening", "readOnly", or "writeOnly". - - - - - -connection.setEncoding(encoding) - - - -Sets the encoding (either "ascii", "utf8", or "binary") for data that is received. - - - - - -connection.send(data, encoding="ascii") - - - -Sends data on the connection. The second parameter specifies the encoding -in the case of a string—it defaults to ASCII because encoding to UTF8 is -rather slow. - - - - - -connection.close() - - - -Half-closes the connection. I.E., it sends a FIN packet. It is -possible the server will still send some data. After calling -this readyState will be "readOnly". - - - - - -connection.forceClose() - - - -Ensures that no more I/O activity happens on this socket. Only -necessary in case of errors (parse error or so). - - - - - -connection.readPause() - - - -Pauses the reading of data. That is, "receive" events will not be emitted. -Useful to throttle back an upload. - - - - - -connection.readResume() - - - -Resumes reading if reading was paused by readPause(). - - - - - -connection.setTimeout(timeout) - - - -Sets the connection to timeout after timeout milliseconds of inactivity on -the connection. By default all tcp.Connection objects have a timeout -of 60 seconds (60000 ms). - -If timeout is 0, then the idle timeout is disabled. - - - - -connection.setNoDelay(noDelay=true) - - - -Disables the Nagle algorithm. By default TCP connections use the Nagle -algorithm, they buffer data before sending it off. Setting noDelay will -immediately fire off data each time connection.send() is called. - - - - - - - -DNS -Here is an example of which resolves "www.google.com" then reverse -resolves the IP addresses which are returned. -var resolution = node.dns.resolve4("www.google.com"); - -resolution.addCallback(function (addresses, ttl, cname) { - puts("addresses: " + JSON.stringify(addresses)); - puts("ttl: " + JSON.stringify(ttl)); - puts("cname: " + JSON.stringify(cname)); - - for (var i = 0; i < addresses.length; i++) { - var a = addresses[i]; - var reversing = node.dns.reverse(a); - reversing.addCallback( function (domains, ttl, cname) { - puts("reverse for " + a + ": " + JSON.stringify(domains)); - }); - reversing.addErrback( function (code, msg) { - puts("reverse for " + a + " failed: " + msg); - }); - } -}); - -resolution.addErrback(function (code, msg) { - puts("error: " + msg); -}); - - - -node.dns.resolve4(domain) - - - -Resolves a domain (e.g. "google.com") into an array of IPv4 addresses (e.g. -["74.125.79.104", "74.125.79.105", "74.125.79.106"]). -This function returns a promise. - - - - -on success: returns addresses, ttl, cname. ttl (time-to-live) is an integer - specifying the number of seconds this result is valid for. cname is the - canonical name for the query. - - - - -on error: returns code, msg. code is one of the error codes listed - below and msg is a string describing the error in English. - - - - - - - -node.dns.resolve6(domain) - - - -The same as node.dns.resolve4() except for IPv6 queries (an AAAA query). - - - - - -node.dns.reverse(ip) - - - -Reverse resolves an ip address to an array of domain names. - - - - -on success: returns domains, ttl, cname. ttl (time-to-live) is an integer - specifying the number of seconds this result is valid for. cname is the - canonical name for the query. domains is an array of domains. - - - - -on error: returns code, msg. code is one of the error codes listed - below and msg is a string describing the error in English. - - - - - - -Each DNS query can return an error code. - - - -node.dns.TEMPFAIL: timeout, SERVFAIL or similar. - - - - -node.dns.PROTOCOL: got garbled reply. - - - - -node.dns.NXDOMAIN: domain does not exists. - - - - -node.dns.NODATA: domain exists but no data of reqd type. - - - - -node.dns.NOMEM: out of memory while processing. - - - - -node.dns.BADQUERY: the query is malformed. - - - - - - -REPL -A Read-Eval-Print-Loop is available both as a standalone program and easily -includable in other programs. -The standalone REPL is called node-repl and is installed at -$PREFIX/bin/node-repl. It’s recommended to use it with the program -rlwrap for a better user interface. I set -alias node-repl="rlwrap node-repl" -in my zsh configuration. -Inside the REPL, Control+D will exit. The special variable _ (underscore) contains the -result of the last expression. -The library is called /repl.js and it can be used like this: -include("/utils.js"); -include("/tcp.js"); -nconnections = 0; -createServer(function (c) { - error("Connection!"); - nconnections += 1; - c.close(); -}).listen(5000); -require("/repl.js").start("simple tcp server> "); - - -Extension API -External modules can be compiled and dynamically linked into Node. -Node is more or less glue between several C and C++ libraries: - - - -V8 Javascript, a C++ library. Used for interfacing with Javascript: - creating objects, calling functions, etc. Documented mostly in the - v8.h header file (deps/v8/include/v8.h in the Node source tree). - - - - -libev, C event loop library. Anytime one needs to wait for a file - descriptor to become readable, wait for a timer, or wait for a signal to - received one will need to interface with libev. That is, if you perform - any I/O, libev will need to be used. Node uses the EV_DEFAULT event - loop. Documentation can be found here. - - - - -libeio, C thread pool library. Used to execute blocking POSIX system - calls asynchronously. Mostly wrappers already exist for such calls, in - src/file.cc so you will probably not need to use it. If you do need it, - look at the header file deps/libeio/eio.h. - - - - -Internal Node libraries. Most importantly is the node::EventEmitter - class which you will likely want to derive from. - - - - -Others. Look in deps/ for what else is available. - - - -Node statically compiles all its dependencies into the executable. When -compiling your module, you don’t need to worry about linking to any of these -libraries. -Here is a sample Makefile taken from -node_postgres: -binding.node: binding.o Makefile - gcc -shared -o binding.node binding.o \ - -L`pg_config --libdir` -lpq - -binding.o: binding.cc Makefile - gcc `node --cflags` -I`pg_config --includedir` \ - binding.cc -c -o binding.o - -clean: - rm -f binding.o binding.node -.PHONY: clean -As you can see, the only thing your module needs to know about Node is the -CFLAGS that node was compiled with which are gotten from node --cflags -If you want to make a debug build, then use node_g --cflags. (node_g is -the debug build of node, which can built with configure --debug; make; make -install.) -Node extension modules are dynamically linked libraries with a .node -extension. Node opens this file and looks for a function called init() -which must be of the form: -extern "C" void init (Handle<Object> target) -In this function you can create new javascript objects and attach them to -target. Here is a very simple module: -extern "C" void -init (Handle<Object> target) -{ - HandleScope scope; - target->Set(String::New("hello"), String::New("World")); -} -Further documentation will come soon. For now see the source code of -node_postgres. - - diff --git a/doc/common.xsl b/doc/common.xsl new file mode 100644 index 0000000000..fdbfb0869e --- /dev/null +++ b/doc/common.xsl @@ -0,0 +1,61 @@ + + + + + + + + + + +./images/icons/ +0 + + + + 0 + #E0E0E0 + + + +./images/icons/ + + + margin-left: 0; margin-right: 10%; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/doc/manpage.xsl b/doc/manpage.xsl new file mode 100644 index 0000000000..6f7d3336ed --- /dev/null +++ b/doc/manpage.xsl @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + diff --git a/doc/node.1 b/doc/node.1 deleted file mode 100644 index 656982fdc1..0000000000 --- a/doc/node.1 +++ /dev/null @@ -1,2044 +0,0 @@ -.\" Title: node -.\" Author: -.\" Generator: DocBook XSL Stylesheets v1.73.2 -.\" Date: 10/03/2009 -.\" Manual: -.\" Source: -.\" -.TH "NODE" "1" "10/03/2009" "" "" -.\" disable hyphenation -.nh -.\" disable justification (adjust text to left margin only) -.ad l -.SH "NAME" -node - evented I/O for V8 javascript -.SH "SYNOPSIS" -An example of a web server written with Node which responds with "Hello World": -.sp -.sp -.RS 4 -.nf -include("/utils\.js"); -include("/http\.js"); -createServer(function (request, response) { - response\.sendHeader(200, {"Content\-Type": "text/plain"}); - response\.sendBody("Hello World\en"); - response\.finish(); -})\.listen(8000); -puts("Server running at http://127\.0\.0\.1:8000/"); -.fi -.RE -To run the server, put the code into a file called example\.js and execute it with the node program -.sp -.sp -.RS 4 -.nf -> node example\.js -Server running at http://127\.0\.0\.1:8000/ -.fi -.RE -.SH "API" -Node supports 3 string encodings\. UTF\-8 ("utf8"), ASCII ("ascii"), and Binary ("binary")\. "ascii" and "binary" only look at the first 8 bits of the 16bit javascript string characters\. Both are relatively fast\(emuse them if you can\. "utf8" is slower and should be avoided when possible\. -.sp -Unless otherwise noted, functions are all asynchronous and do not block execution\. -.sp -.SS "Helpers" -These objects are available to all programs\. -.PP -node\.cwd() -.RS 4 -Returns the current working directory of the process\. -.RE -.PP -node\.compile(source, scriptOrigin) -.RS 4 -Just like -eval() -except that you can specify a -scriptOrigin -for better error reporting\. -.RE -.PP -__filename -.RS 4 -The filename of the script being executed\. -.RE -.PP -require(path), include(path) -.RS 4 -See the modules section\. -.RE -.PP -node\.libraryPaths -.RS 4 -The search path for absolute path arguments to -require() -and -include()\. -.RE -.SS "The process Object" -process is the equivalent of window in browser\-side javascript\. It is the global scope\. process is an instance of node\.EventEmitter\. -.sp -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt. -T{ -"exit" -.sp -T}:T{ -code -.sp -T}:T{ -Made when the process exits\. A listener on this event should not try to perform I/O since the process will forcibly exit in less than microsecond\. However, it is a good hook to perform constant time checks of the module\(cqs state (like for unit tests)\. The parameter code is the integer exit code passed to process\.exit()\. -.sp -T} -.TE -.PP -process\.exit(code=0) -.RS 4 -Ends the process with the specified code\. By default it exits with the success code 0\. -.RE -.PP -process\.ARGV -.RS 4 -An array containing the command line arguments\. -.RE -.PP -process\.ENV -.RS 4 -An object containing the user environment\. See environ(7)\. -.RE -.SS "Utilities" -These function are in "/utils\.js"\. Use require("/utils\.js") to access them\. -.PP -puts(string) -.RS 4 -Outputs the -string -and a trailing new\-line to -stdout\. -.RE -.PP -print(string) -.RS 4 -Like -puts() -but without the trailing new\-line\. -.RE -.PP -debug(string) -.RS 4 -A synchronous output function\. Will block the process and output the string immediately to stdout\. -.RE -.PP -inspect(object) -.RS 4 -Return a string representation of the -object\. (For debugging\.) -.RE -.PP -exec(command) -.RS 4 -Executes the command as a child process, buffers the output and returns it in a promise callback\. -.sp -.RS 4 -.nf -include("/utils\.js"); -exec("ls /")\.addCallback(function (stdout, stderr) { - puts(stdout); -}); -.fi -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: stdout buffer, stderr buffer -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: exit code, stdout buffer, stderr buffer -.RE -.RE -.SS "Events" -Many objects in Node emit events: a TCP server emits an event each time there is a connection, a child process emits an event when it exits\. All objects which emit events are are instances of node\.EventEmitter\. -.sp -Events are represented by a camel\-cased string\. Here are some examples: "connection", "receive", "messageBegin"\. -.sp -Functions can be then be attached to objects, to be executed when an event is emitted\. These functions are called \fIlisteners\fR\. -.sp -Some asynchronous file operations return an EventEmitter called a \fIpromise\fR\. A promise emits just a single event when the operation is complete\. -.sp -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -node.EventEmitter -.RS -All EventEmitters emit the event "newListener" when new listeners are added\. -.sp -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt. -T{ -"newListener" -.sp -T}:T{ -event, listener -.sp -T}:T{ -This event is made any time someone adds a new listener\. -.sp -T} -.TE -.PP -emitter\.addListener(event, listener) -.RS 4 -Adds a listener to the end of the listeners array for the specified event\. -.sp -.RS 4 -.nf -server\.addListener("connection", function (socket) { - puts("someone connected!"); -}); -.fi -.RE -.RE -.PP -emitter\.listeners(event) -.RS 4 -Returns an array of listeners for the specified event\. This array can be manipulated, e\.g\. to remove listeners\. -.RE -.PP -emitter\.emit(event, arg1, arg2, \&...) -.RS 4 -Execute each of the listeners in order with the supplied arguments\. -.RE -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -node.Promise -.RS -node\.Promise inherits from node\.eventEmitter\. A promise emits one of two events: "success" or "error"\. After emitting its event, it will not emit anymore events\. -.sp -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt -lt lt lt. -T{ -"success" -.sp -T}:T{ -(depends) -.sp -T}:T{ -.sp -T} -T{ -"error" -.sp -T}:T{ -(depends) -.sp -T}:T{ -.sp -T} -.TE -.PP -promise\.addCallback(listener) -.RS 4 -Adds a listener for the -"success" -event\. Returns the same promise object\. -.RE -.PP -promise\.addErrback(listener) -.RS 4 -Adds a listener for the -"error" -event\. Returns the same promise object\. -.RE -.PP -promise\.emitSuccess(arg1, arg2, \&...) -.RS 4 -If you created the promise (by doing -new node\.Promise()) then call -emitSuccess -to emit the -"success" -event with the given arguments\. -.sp -(promise\.emit("success", arg1, arg2, \&...) -should also work, but doesn\(cqt at the moment due to a bug; use -emitSuccess -instead\.) -.RE -.PP -promise\.emitError(arg1, arg2, \&...) -.RS 4 -Emits the -"error" -event\. -.RE -.PP -promise\.wait() -.RS 4 -Blocks futher execution until the promise emits a success or error event\. Events setup before the call to -promise\.wait() -was made may still be emitted and executed while -promise\.wait() -is blocking\. -.sp -If there was a single argument to the -"success" -event then it is returned\. If there were multiple arguments to -"success" -then they are returned as an array\. -.sp -If -"error" -was emitted instead, -wait() -throws an error\. -.sp -\fBIMPORTANT\fR -promise\.wait() -is not a true fiber/coroutine\. If any other promises are created and made to wait while the first promise waits, the first promise\(cqs wait will not return until all others return\. The benefit of this is a simple implementation and the event loop does not get blocked\. Disadvantage is the possibility of situations where the promise stack grows infinitely large because promises keep getting created and keep being told to wait()\. Use -promise\.wait() -sparingly\(emprobably best used only during program setup, not during busy server activity\. -.RE -.RE -.SS "Standard I/O" -Standard I/O is handled through a special object node\.stdio\. stdout and stdin are fully non\-blocking (even when piping to files)\. stderr is synchronous\. -.sp -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt -lt lt lt. -T{ -"data" -.sp -T}:T{ -data -.sp -T}:T{ -Made when stdin has received a chunk of data\. Depending on the encoding that stdin was opened with, data will be a string\. This event will only be emited after node\.stdio\.open() has been called\. -.sp -T} -T{ -"close" -.sp -T}:T{ -.sp -T}:T{ -Made when stdin has been closed\. -.sp -T} -.TE -.PP -node\.stdio\.open(encoding="utf8") -.RS 4 -Open stdin\. The program will not exit until -node\.stdio\.close() -has been called or the -"close" -event has been emitted\. -.RE -.PP -node\.stdio\.write(data) -.RS 4 -Write data to stdout\. -.RE -.PP -node\.stdio\.writeError(data) -.RS 4 -Write data to stderr\. Synchronous\. -.RE -.PP -node\.stdio\.close() -.RS 4 -Close stdin\. -.RE -.SS "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 circle\.js\. -.sp -The contents of foo\.js: -.sp -.sp -.RS 4 -.nf -var circle = require("circle\.js"); -include("/utils\.js"); -puts("The area of a circle of radius 4 is " + circle\.area(4)); -.fi -.RE -The contents of circle\.js: -.sp -.sp -.RS 4 -.nf -var PI = 3\.14; - -exports\.area = function (r) { - return PI * r * r; -}; - -exports\.circumference = function (r) { - return 2 * PI * r; -}; -.fi -.RE -The module circle\.js has exported the functions area() and circumference()\. To export an object, add to the special exports object\. (Alternatively, one can use this instead of exports\.) Variables local to the module will be private\. In this example the variable PI is private to circle\.js\. The function puts() comes from the module "/utils\.js"\. Because include("/utils\.js") was called, puts() is in the global namespace\. -.sp -The module path is relative to the file calling require()\. That is, circle\.js must be in the same directory as foo\.js for require() to find it\. -.sp -Like require() the function include() also loads a module\. Instead of returning a namespace object, include() will add the module\(cqs exports into the global namespace\. For example: -.sp -.sp -.RS 4 -.nf -include("circle\.js"); -include("/utils\.js"); -puts("The area of a cirlce of radius 4 is " + area(4)); -.fi -.RE -When an absolute path is given to require() or include(), like require("/mjsunit\.js") the module is searched for in the node\.libraryPaths array\. node\.libraryPaths on my system looks like this: -.sp -.sp -.RS 4 -.nf -[ "/home/ryan/\.node_libraries" -, "/home/ryan/local/node/lib/node_libraries" -, "/" -] -.fi -.RE -That is, first Node looks for "/home/ryan/\.node_libraries/mjsunit\.js" and then for "/home/ryan/local/node/lib/node_libraries/mjsunit\.js"\. If not found, it finally looks for "/mjsunit\.js" (in the root directory)\. -.sp -node\.libraryPaths can be modified at runtime by simply unshifting new paths on to it and at startup with the NODE_LIBRARY_PATHS environmental variable (which should be a list of paths, colon separated)\. -.sp -Node comes with several libraries which are installed when "make install" is run\. These are currently undocumented, but do look them up in your system\. -.sp -.SS "Timers" -.PP -setTimeout(callback, delay) -.RS 4 -To schedule execution of callback after delay milliseconds\. Returns a -timeoutId -for possible use with -clearTimeout()\. -.RE -.PP -clearTimeout(timeoutId) -.RS 4 -Prevents said timeout from triggering\. -.RE -.PP -setInterval(callback, delay) -.RS 4 -To schedule the repeated execution of callback every -delay -milliseconds\. Returns a -intervalId -for possible use with -clearInterval()\. -.RE -.PP -clearInterval(intervalId) -.RS 4 -Stops a interval from triggering\. -.RE -.SS "Child Processes" -Node provides a tridirectional popen(3) facility through the class node\.ChildProcess\. It is possible to stream data through the child\(cqs stdin, stdout, and stderr in a fully non\-blocking way\. -.sp -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -node.ChildProcess -.RS -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt -lt lt lt -lt lt lt. -T{ -"output" -.sp -T}:T{ -data -.sp -T}:T{ -Each time the child process sends data to its stdout, this event is emitted\. data is a string\. + If the child process closes its stdout stream (a common thing to do on exit), this event will be emitted with data === null\. -.sp -T} -T{ -"error" -.sp -T}:T{ -data -.sp -T}:T{ -Identical to the "output" event except for stderr instead of stdout\. -.sp -T} -T{ -"exit" -.sp -T}:T{ -code -.sp -T}:T{ -This event is emitted after the child process ends\. code is the final exit code of the process\. One can be assured that after this event is emitted that the "output" and "error" callbacks will no longer be made\. -.sp -T} -.TE -.PP -node\.createChildProcess(command) -.RS 4 -Launches a new process with the given -command\. For example: -.sp -.RS 4 -.nf -var ls = node\.createChildProcess("ls \-lh /usr"); -ls\.addListener("output", function (data) { - puts(data); -}); -.fi -.RE -.RE -.PP -child\.pid -.RS 4 -The PID of the child process\. -.RE -.PP -child\.write(data, encoding="ascii") -.RS 4 -Write data to the child process\(cqs -stdin\. The second argument is optional and specifies the encoding: possible values are -"utf8", -"ascii", and -"binary"\. -.RE -.PP -child\.close() -.RS 4 -Closes the process\(cqs -stdin -stream\. -.RE -.PP -child\.kill(signal=node\.SIGTERM) -.RS 4 -Send a single to the child process\. If no argument is given, the process will be sent -node\.SIGTERM\. The standard POSIX signals are defined under the -node -namespace (node\.SIGINT, -node\.SIGUSR1, \&...)\. -.RE -.RE -.SS "File I/O" -File I/O is provided by simple wrappers around standard POSIX functions\. All POSIX wrappers have a similar form\. They return a promise (node\.Promise)\. Example: -.sp -.sp -.RS 4 -.nf -var promise = node\.fs\.unlink("/tmp/hello"); -promise\.addCallback(function () { - puts("successfully deleted /tmp/hello"); -}); -.fi -.RE -There is no guaranteed ordering to the POSIX wrappers\. The following is very much prone to error -.sp -.sp -.RS 4 -.nf -node\.fs\.rename("/tmp/hello", "/tmp/world"); -node\.fs\.stat("/tmp/world")\.addCallback(function (stats) { - puts("stats: " + JSON\.stringify(stats)); -}); -.fi -.RE -It could be that stat() is executed before the rename()\. The correct way to do this is to chain the promises\. -.sp -.sp -.RS 4 -.nf -node\.fs\.rename("/tmp/hello", "/tmp/world")\.addCallback(function () { - node\.fs\.stat("/tmp/world")\.addCallback(function (stats) { - puts("stats: " + JSON\.stringify(stats)); - }); -}); -.fi -.RE -Or use the promise\.wait() functionality: -.sp -.sp -.RS 4 -.nf -node\.fs\.rename("/tmp/hello", "/tmp/world")\.wait(); -node\.fs\.stat("/tmp/world")\.addCallback(function (stats) { - puts("stats: " + JSON\.stringify(stats)); -}); -.fi -.RE -.PP -node\.fs\.rename(path1, path2) -.RS 4 -See rename(2)\. -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: no parameters\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: no parameters\. -.RE -.RE -.PP -node\.fs\.stat(path) -.RS 4 -See stat(2)\. -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: Returns -node\.fs\.Stats -object\. It looks like this: -{ dev: 2049, ino: 305352, mode: 16877, nlink: 12, uid: 1000, gid: 1000, rdev: 0, size: 4096, blksize: 4096, blocks: 8, atime: "2009\-06\-29T11:11:55Z", mtime: "2009\-06\-29T11:11:40Z", ctime: "2009\-06\-29T11:11:40Z" } -See the -node\.fs\.Stats -section below for more information\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: no parameters\. -.RE -.RE -.PP -node\.fs\.unlink(path) -.RS 4 -See unlink(2) -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: no parameters\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: no parameters\. -.RE -.RE -.PP -node\.fs\.rmdir(path) -.RS 4 -See rmdir(2) -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: no parameters\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: no parameters\. -.RE -.RE -.PP -node\.fs\.mkdir(path, mode) -.RS 4 -See mkdir(2) -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: no parameters\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: no parameters\. -.RE -.RE -.PP -node\.fs\.readdir(path) -.RS 4 -Reads the contents of a directory\. -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: One argument, an array containing the names (strings) of the files in the directory (excluding "\." and "\.\.")\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: no parameters\. -.RE -.RE -.PP -node\.fs\.close(fd) -.RS 4 -See close(2) -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: no parameters\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: no parameters\. -.RE -.RE -.PP -node\.fs\.open(path, flags, mode) -.RS 4 -See open(2)\. The constants like -O_CREAT -are defined at -node\.O_CREAT\. -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: -fd -is given as the parameter\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: no parameters\. -.RE -.RE -.PP -node\.fs\.write(fd, data, position, encoding) -.RS 4 -Write data to the file specified by -fd\. -position -refers to the offset from the beginning of the file where this data should be written\. If -position -is -null, the data will be written at the current position\. See pwrite(2)\. -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: returns an integer -written -which specifies how many -\fIbytes\fR -were written\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: no parameters\. -.RE -.RE -.PP -node\.fs\.read(fd, length, position, encoding) -.RS 4 -Read data from the file specified by -fd\. -.sp -length -is an integer specifying the number of bytes to read\. -.sp -position -is an integer specifying where to begin reading from in the file\. -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: returns -data, bytes_read, what was read from the file\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: no parameters\. -.RE -.RE -.PP -node\.fs\.cat(filename, encoding="utf8") -.RS 4 -Outputs the entire contents of a file\. Example: -.sp -.RS 4 -.nf -node\.fs\.cat("/etc/passwd")\.addCallback(function (content) { - puts(content); -}); -.fi -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: returns -data, what was read from the file\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: no parameters\. -.RE -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -node.fs.Stats -.RS -Objects returned from node\.fs\.stat() are of this type\. -.PP -stats\.isFile(), stats\.isDirectory(), stats\.isBlockDevice(), stats\.isCharacterDevice(), stats\.isSymbolicLink(), stats\.isFIFO(), stats\.isSocket() -.RS 4 -\&... -.RE -.RE -.SS "HTTP" -To use the HTTP server and client one must require("/http\.js") or include("/http\.js")\. -.sp -The HTTP interfaces in Node are designed to support many features of the protocol which have been traditionally difficult to use\. In particular, large, possibly chunk\-encoded, messages\. The interface is careful to never buffer entire requests or responses\(emthe user is able to stream data\. -.sp -HTTP message headers are represented by an object like this -.sp -.sp -.RS 4 -.nf -{ "Content\-Length": "123" -, "Content\-Type": "text/plain" -, "Connection": "keep\-alive" -, "Accept": "*/*" -} -.fi -.RE -In order to support the full spectrum of possible HTTP applications, Node\(cqs HTTP API is very low\-level\. It deals with connection handling and message parsing only\. It parses a message into headers and body but it does not parse the actual headers or the body\. -.sp -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -http.Server -.RS -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt -lt lt lt -lt lt lt. -T{ -"request" -.sp -T}:T{ -request, response -.sp -T}:T{ -request is an instance of http\.ServerRequest response is an instance of http\.ServerResponse -.sp -T} -T{ -"connection" -.sp -T}:T{ -connection -.sp -T}:T{ -When a new TCP connection is established\. connection is an object of type http\.Connection\. Usually users will not want to access this event\. The connection can also be accessed at request\.connection\. -.sp -T} -T{ -"close" -.sp -T}:T{ -errorno -.sp -T}:T{ -Emitted when the server closes\. errorno is an integer which indicates what, if any, error caused the server to close\. If no error occured errorno will be 0\. -.sp -T} -.TE -.PP -http\.createServer(request_listener, options); -.RS 4 -Returns a new web server object\. -.sp -The -options -argument is optional\. The -options -argument accepts the same values as the options argument for -tcp\.Server -does\. -.sp -The -request_listener -is a function which is automatically added to the -"request" -event\. -.RE -.PP -server\.listen(port, hostname) -.RS 4 -Begin accepting connections on the specified port and hostname\. If the hostname is omitted, the server will accept connections directed to any address\. This function is synchronous\. -.RE -.PP -server\.close() -.RS 4 -Stops the server from accepting new connections\. -.RE -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -http.ServerRequest -.RS -This object is created internally by a HTTP server\(emnot by the user\(emand passed as the first argument to a "request" listener\. -.sp -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt -lt lt lt. -T{ -"body" -.sp -T}:T{ -chunk -.sp -T}:T{ -Emitted when a piece of the message body is received\. Example: A chunk of the body is given as the single argument\. The transfer\-encoding has been decoded\. The body chunk is a String\. The body encoding is set with request\.setBodyEncoding()\. -.sp -T} -T{ -"complete" -.sp -T}:T{ -(none) -.sp -T}:T{ -Emitted exactly once for each message\. No arguments\. After emitted no other events will be emitted on the request\. -.sp -T} -.TE -.PP -request\.method -.RS 4 -The request method as a string\. Read only\. Example: -"GET", -"DELETE"\. -.RE -.PP -request\.uri -.RS 4 -Request URI Object\. This contains only the parameters that are present in the actual HTTP request\. That is, if the request is -.sp -.RS 4 -.nf -GET /status?name=ryan HTTP/1\.1\er\en -Accept: text/plain\er\en -\er\en -.fi -.RE -Then -request\.uri -will be -.sp -.RS 4 -.nf -{ path: "/status", - file: "status", - directory: "/", - params: { "name" : "ryan" } -} -.fi -.RE -In particular, note that -request\.uri\.protocol -is -undefined\. This is because there was no URI protocol given in the actual HTTP Request\. -.sp -Here is what\(cqs available: -request\.uri\.anchor, -request\.uri\.query, -request\.uri\.file, -request\.uri\.directory, -request\.uri\.path, -request\.uri\.relative, -request\.uri\.port, -request\.uri\.host, -request\.uri\.password, -request\.uri\.user, -request\.uri\.authority, -request\.uri\.protocol, -request\.uri\.params, -request\.uri\.toString(), -request\.uri\.source -.RE -.PP -request\.headers -.RS 4 -Read only\. -.RE -.PP -request\.httpVersion -.RS 4 -The HTTP protocol version as a string\. Read only\. Examples: -"1\.1", -"1\.0" -.RE -.PP -request\.setBodyEncoding(encoding) -.RS 4 -Set the encoding for the request body\. Either -"utf8" -or -"binary"\. Defaults to -"binary"\. -.RE -.PP -request\.pause() -.RS 4 -Pauses request from emitting events\. Useful to throttle back an upload\. -.RE -.PP -request\.resume() -.RS 4 -Resumes a paused request\. -.RE -.PP -request\.connection -.RS 4 -The -http\.Connection -object\. -.RE -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -http.ServerResponse -.RS -This object is created internally by a HTTP server\(emnot by the user\. It is passed as the second parameter to the "request" event\. -.PP -response\.sendHeader(statusCode, headers) -.RS 4 -Sends a response header to the request\. The status code is a 3\-digit HTTP status code, like -404\. The second argument, -headers -are the response headers\. -.sp -Example: -.sp -.RS 4 -.nf -var body = "hello world"; -response\.sendHeader(200, { - "Content\-Length": body\.length, - "Content\-Type": "text/plain" -}); -.fi -.RE -This method must only be called once on a message and it must be called before -response\.finish() -is called\. -.RE -.PP -response\.sendBody(chunk, encoding="ascii") -.RS 4 -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\. -.sp -If -chunk -is a string, the second parameter specifies how to encode it into a byte stream\. By default the -encoding -is -"ascii"\. -.sp -Note: This is the raw HTTP body and has nothing to do with higher\-level multi\-part body encodings that may be used\. -.sp -The first time -sendBody -is called, it will send the buffered header information and the first body to the client\. The second time -sendBody -is called, Node assumes you\(cqre going to be streaming data, and sends that seperately\. That is, the response is buffered up to the first chunk of body\. -.RE -.PP -response\.finish() -.RS 4 -This method signals to the server that all of the response headers and body has been sent; that server should consider this message complete\. The method, -response\.finish(), MUST be called on each response\. -.RE -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -http.Client -.RS -An HTTP client is constructed with a server address as its argument, the returned handle is then used to issue one or more requests\. Depending on the server connected to, the client might pipeline the requests or reestablish the connection after each connection\. \fICurrently the implementation does not pipeline requests\.\fR -.sp -Example of connecting to google\.com -.sp -.sp -.RS 4 -.nf -var google = http\.createClient(80, "google\.com"); -var request = google\.get("/"); -request\.finish(function (response) { - puts("STATUS: " + response\.statusCode); - puts("HEADERS: " + JSON\.stringify(response\.headers)); - response\.setBodyEncoding("utf8"); - response\.addListener("body", function (chunk) { - puts("BODY: " + chunk); - }); -}); -.fi -.RE -.PP -http\.createClient(port, host) -.RS 4 -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\. -.RE -.PP -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) -.RS 4 -Issues a request; if necessary establishes connection\. Returns a -http\.ClientRequest -instance\. -.sp -request_headers -is optional\. Additional request headers might be added internally by Node\. Returns a -ClientRequest -object\. -.sp -Do remember to include the -Content\-Length -header if you plan on sending a body\. If you plan on streaming the body, perhaps set -Transfer\-Encoding: chunked\. -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -Note -the request is not complete\. This method only sends the header of the request\. One needs to call -request\.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 -request\.sendBody()\.) -.RE -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -http.ClientRequest -.RS -This object is created internally and returned from the request methods of a http\.Client\. It represents an \fIin\-progress\fR request whose header has already been sent\. -.sp -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt. -T{ -"response" -.sp -T}:T{ -response -.sp -T}:T{ -Emitted when a response is received to this request\. Typically the user will set a listener to this via the request\.finish() method\. This event is emitted only once\. The response argument will be an instance of http\.ClientResponse\. -.sp -T} -.TE -.PP -request\.sendBody(chunk, encoding="ascii") -.RS 4 -Sends a chunk of the body\. By calling this method many times, the user can stream a request body to a server\(emin that case it is suggested to use the -["Transfer\-Encoding", "chunked"] -header line when creating the request\. -.sp -The -chunk -argument should be an array of integers or a string\. -.sp -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\. -.RE -.PP -request\.finish(responseListener) -.RS 4 -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\er\en\er\en"\. -.sp -The parameter -responseListener -is a callback which will be executed when the response headers have been received\. The -responseListener -callback is executed with one argument which is an instance of -http\.ClientResponse\. -.sp -In the -responseListener -callback, one can add more listeners to the response, in particular listening for the -"body" -event\. Note that the -responseListener -is called before any part of the body is receieved, so there is no need to worry about racing to catch the first part of the body\. As long as a listener for -"body" -is added during the -responseListener -callback, the entire body will be caught\. -.sp -.RS 4 -.nf -// Good -request\.finish(function (response) { - response\.addListener("body", function (chunk) { - puts("BODY: " + chunk); - }); -}); - -// Bad \- misses all or part of the body -request\.finish(function (response) { - setTimeout(function () { - response\.addListener("body", function (chunk) { - puts("BODY: " + chunk); - }); - }, 10); -}); -.fi -.RE -.RE -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -http.ClientResponse -.RS -This object is created internally and passed to the "response" event\. -.sp -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt -lt lt lt. -T{ -"body" -.sp -T}:T{ -chunk -.sp -T}:T{ -Emitted when a piece of the message body is received\. Example: A chunk of the body is given as the single argument\. The transfer\-encoding has been decoded\. The body chunk a String\. The body encoding is set with response\.setBodyEncoding()\. -.sp -T} -T{ -"complete" -.sp -T}:T{ -.sp -T}:T{ -Emitted exactly once for each message\. No arguments\. After emitted no other events will be emitted on the response\. -.sp -T} -.TE -.PP -response\.statusCode -.RS 4 -The 3\-digit HTTP response status code\. E\.G\. -404\. -.RE -.PP -response\.httpVersion -.RS 4 -The HTTP version of the connected\-to server\. Probably either -"1\.1" -or -"1\.0"\. -.RE -.PP -response\.headers -.RS 4 -The response headers\. -.RE -.PP -response\.setBodyEncoding(encoding) -.RS 4 -Set the encoding for the response body\. Either -"utf8" -or -"binary"\. Defaults to -"binary"\. -.RE -.PP -response\.pause() -.RS 4 -Pauses response from emitting events\. Useful to throttle back a download\. -.RE -.PP -response\.resume() -.RS 4 -Resumes a paused response\. -.RE -.PP -response\.client -.RS 4 -A reference to the -http\.Client -that this response belongs to\. -.RE -.RE -.SS "Multipart Parsing" -A library to parse HTTP requests with multipart/form\-data is included with Node\. To use it, require("/multipart\.js")\. -.PP -multipart\.parse(options) -.RS 4 -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: Returns an object where each key holds the value of one part of the stream\. -options -can either be an instance of -http\.ServerRequest -or an object containing a -\fIboundary\fR -and a -\fIdata\fR -key\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: no parameters\. -.RE -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -multipart.Stream -.RS -Here is an example for parsing a multipart/form\-data request: -.sp -.sp -.RS 4 -.nf -var multipart = require(\'/multipart\.js\'); -var stream = new multipart\.Stream(options); -var parts = {}; - -stream\.addListener(\'part\', function (part) { - var name = part\.headers[\'Content\-Disposition\']\.name; - var buffer = \'\'; - - part\.addListener(\'body\', function(chunk) { - buffer = buffer + chunk; - }); - - part\.addListener(\'complete\', function() { - parts[name] = buffer; - }); -}); - -stream\.addListener(\'complete\', function() { - // The parts object now contains all parts and data -}); -.fi -.RE -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt -lt lt lt. -T{ -"part" -.sp -T}:T{ -part -.sp -T}:T{ -Emitted when a new part is found in the stream\. part is an instance of multipart\.Part\. -.sp -T} -T{ -"complete" -.sp -T}:T{ -.sp -T}:T{ -Emitted when the end of the stream is reached\. -.sp -T} -.TE -.sp -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -multipart.Part -.RS -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt -lt lt lt. -T{ -"body" -.sp -T}:T{ -chunk -.sp -T}:T{ -Emitted when a chunk of body is read\. -.sp -T} -T{ -"complete" -.sp -T}:T{ -.sp -T}:T{ -Emitted when the end of the part is reached\. -.sp -T} -.TE -.sp -.RE -.SS "TCP" -To use the TCP server and client one must require("/tcp\.js") or include("/tcp\.js")\. -.sp -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -tcp.Server -.RS -Here is an example of a echo server which listens for connections on port 7000 -.sp -.sp -.RS 4 -.nf -include("/tcp\.js"); -var server = createServer(function (socket) { - socket\.setEncoding("utf8"); - socket\.addListener("connect", function () { - socket\.send("hello\er\en"); - }); - socket\.addListener("receive", function (data) { - socket\.send(data); - }); - socket\.addListener("eof", function () { - socket\.send("goodbye\er\en"); - socket\.close(); - }); -}); -server\.listen(7000, "localhost"); -.fi -.RE -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt -lt lt lt. -T{ -"connection" -.sp -T}:T{ -connection -.sp -T}:T{ -Emitted when a new connection is made\. connection is an instance of tcp\.Connection\. -.sp -T} -T{ -"close" -.sp -T}:T{ -errorno -.sp -T}:T{ -Emitted when the server closes\. errorno is an integer which indicates what, if any, error caused the server to close\. If no error occurred errorno will be 0\. -.sp -T} -.TE -.PP -tcp\.createServer(connection_listener); -.RS 4 -Creates a new TCP server\. -.sp -The -connection_listener -argument is automatically set as a listener for the -"connection" -event\. -.RE -.PP -server\.listen(port, host=null, backlog=128) -.RS 4 -Tells the server to listen for TCP connections to -port -and -host\. -.sp -host -is optional\. If -host -is not specified the server will accept client connections on any network address\. -.sp -The third argument, -backlog, is also optional and defaults to 128\. The -backlog -argument defines the maximum length to which the queue of pending connections for the server may grow\. -.sp -This function is synchronous\. -.RE -.PP -server\.close() -.RS 4 -Stops the server from accepting new connections\. This function is asynchronous, the server is finally closed when the server emits a -"close" -event\. -.RE -.RE -.sp -.it 1 an-trap -.nr an-no-space-flag 1 -.nr an-break-flag 1 -.br -tcp.Connection -.RS -This object is used as a TCP client and also as a server\-side socket for tcp\.Server\. -.sp -.TS -allbox tab(:); -ltB ltB ltB. -T{ -Event -T}:T{ -Parameters -T}:T{ -Notes -T} -.T& -lt lt lt -lt lt lt -lt lt lt -lt lt lt -lt lt lt. -T{ -"connect" -.sp -T}:T{ -.sp -T}:T{ -Call once the connection is established after a call to createConnection() or connect()\. -.sp -T} -T{ -"receive" -.sp -T}:T{ -data -.sp -T}:T{ -Called when data is received on the connection\. data will be a string\. Encoding of data is set by connection\.setEncoding()\. -.sp -T} -T{ -"eof" -.sp -T}:T{ -.sp -T}:T{ -Called when the other end of the connection sends a FIN packet\. After this is emitted the readyState will be "writeOnly"\. One should probably just call connection\.close() when this event is emitted\. -.sp -T} -T{ -"timeout" -.sp -T}:T{ -.sp -T}:T{ -Emitted if the connection times out from inactivity\. The "close" event will be emitted immediately following this event\. -.sp -T} -T{ -"close" -.sp -T}:T{ -had_error -.sp -T}:T{ -Emitted once the connection is fully closed\. The argument had_error is a boolean which says if the connection was closed due to a transmission error\. (TODO: access error codes\.) -.sp -T} -.TE -.PP -tcp\.createConnection(port, host="127\.0\.0\.1") -.RS 4 -Creates a new connection object and opens a connection to the specified -port -and -host\. If the second parameter is omitted, localhost is assumed\. -.sp -When the connection is established the -"connect" -event will be emitted\. -.RE -.PP -connection\.connect(port, host="127\.0\.0\.1") -.RS 4 -Opens a connection to the specified -port -and -host\. -createConnection() -also opens a connection; normally this method is not needed\. Use this only if a connection is closed and you want to reuse the object to connect to another server\. -.sp -This function is asynchronous\. When the -"connect" -event is emitted the connection is established\. If there is a problem connecting, the -"connect" -event will not be emitted, the -"close" -event will be emitted with -had_error == true\. -.RE -.PP -connection\.remoteAddress -.RS 4 -The string representation of the remote IP address\. For example, -"74\.125\.127\.100" -or -"2001:4860:a005::68"\. -.sp -This member is only present in server\-side connections\. -.RE -.PP -connection\.readyState -.RS 4 -Either -"closed", -"open", -"opening", -"readOnly", or -"writeOnly"\. -.RE -.PP -connection\.setEncoding(encoding) -.RS 4 -Sets the encoding (either -"ascii", -"utf8", or -"binary") for data that is received\. -.RE -.PP -connection\.send(data, encoding="ascii") -.RS 4 -Sends data on the connection\. The second parameter specifies the encoding in the case of a string\(emit defaults to ASCII because encoding to UTF8 is rather slow\. -.RE -.PP -connection\.close() -.RS 4 -Half\-closes the connection\. I\.E\., it sends a FIN packet\. It is possible the server will still send some data\. After calling this -readyState -will be -"readOnly"\. -.RE -.PP -connection\.forceClose() -.RS 4 -Ensures that no more I/O activity happens on this socket\. Only necessary in case of errors (parse error or so)\. -.RE -.PP -connection\.readPause() -.RS 4 -Pauses the reading of data\. That is, -"receive" -events will not be emitted\. Useful to throttle back an upload\. -.RE -.PP -connection\.readResume() -.RS 4 -Resumes reading if reading was paused by -readPause()\. -.RE -.PP -connection\.setTimeout(timeout) -.RS 4 -Sets the connection to timeout after -timeout -milliseconds of inactivity on the connection\. By default all -tcp\.Connection -objects have a timeout of 60 seconds (60000 ms)\. -.sp -If -timeout -is 0, then the idle timeout is disabled\. -.RE -.PP -connection\.setNoDelay(noDelay=true) -.RS 4 -Disables the Nagle algorithm\. By default TCP connections use the Nagle algorithm, they buffer data before sending it off\. Setting -noDelay -will immediately fire off data each time -connection\.send() -is called\. -.RE -.RE -.SS "DNS" -Here is an example of which resolves "www\.google\.com" then reverse resolves the IP addresses which are returned\. -.sp -.sp -.RS 4 -.nf -var resolution = node\.dns\.resolve4("www\.google\.com"); - -resolution\.addCallback(function (addresses, ttl, cname) { - puts("addresses: " + JSON\.stringify(addresses)); - puts("ttl: " + JSON\.stringify(ttl)); - puts("cname: " + JSON\.stringify(cname)); - - for (var i = 0; i < addresses\.length; i++) { - var a = addresses[i]; - var reversing = node\.dns\.reverse(a); - reversing\.addCallback( function (domains, ttl, cname) { - puts("reverse for " + a + ": " + JSON\.stringify(domains)); - }); - reversing\.addErrback( function (code, msg) { - puts("reverse for " + a + " failed: " + msg); - }); - } -}); - -resolution\.addErrback(function (code, msg) { - puts("error: " + msg); -}); -.fi -.RE -.PP -node\.dns\.resolve4(domain) -.RS 4 -Resolves a domain (e\.g\. -"google\.com") into an array of IPv4 addresses (e\.g\. -["74\.125\.79\.104", "74\.125\.79\.105", "74\.125\.79\.106"])\. This function returns a promise\. -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: returns -addresses, ttl, cname\. -ttl -(time\-to\-live) is an integer specifying the number of seconds this result is valid for\. -cname -is the canonical name for the query\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: returns -code, msg\. -code -is one of the error codes listed below and -msg -is a string describing the error in English\. -.RE -.RE -.PP -node\.dns\.resolve6(domain) -.RS 4 -The same as -node\.dns\.resolve4() -except for IPv6 queries (an -AAAA -query)\. -.RE -.PP -node\.dns\.reverse(ip) -.RS 4 -Reverse resolves an ip address to an array of domain names\. -.sp -.RS 4 -\h'-04'\(bu\h'+03'on success: returns -domains, ttl, cname\. -ttl -(time\-to\-live) is an integer specifying the number of seconds this result is valid for\. -cname -is the canonical name for the query\. -domains -is an array of domains\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'on error: returns -code, msg\. -code -is one of the error codes listed below and -msg -is a string describing the error in English\. -.RE -.RE -Each DNS query can return an error code\. -.sp -.sp -.RS 4 -\h'-04'\(bu\h'+03' -node\.dns\.TEMPFAIL: timeout, SERVFAIL or similar\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03' -node\.dns\.PROTOCOL: got garbled reply\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03' -node\.dns\.NXDOMAIN: domain does not exists\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03' -node\.dns\.NODATA: domain exists but no data of reqd type\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03' -node\.dns\.NOMEM: out of memory while processing\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03' -node\.dns\.BADQUERY: the query is malformed\. -.RE -.SH "REPL" -A Read\-Eval\-Print\-Loop is available both as a standalone program and easily includable in other programs\. -.sp -The standalone REPL is called node\-repl and is installed at $PREFIX/bin/node\-repl\. It\(cqs recommended to use it with the program rlwrap for a better user interface\. I set -.sp -.sp -.RS 4 -.nf -alias node\-repl="rlwrap node\-repl" -.fi -.RE -in my zsh configuration\. -.sp -Inside the REPL, Control+D will exit\. The special variable _ (underscore) contains the result of the last expression\. -.sp -The library is called /repl\.js and it can be used like this: -.sp -.sp -.RS 4 -.nf -include("/utils\.js"); -include("/tcp\.js"); -nconnections = 0; -createServer(function (c) { - error("Connection!"); - nconnections += 1; - c\.close(); -})\.listen(5000); -require("/repl\.js")\.start("simple tcp server> "); -.fi -.RE -.SH "EXTENSION API" -External modules can be compiled and dynamically linked into Node\. Node is more or less glue between several C and C++ libraries: -.sp -.sp -.RS 4 -\h'-04'\(bu\h'+03'V8 Javascript, a C++ library\. Used for interfacing with Javascript: creating objects, calling functions, etc\. Documented mostly in the -v8\.h -header file (deps/v8/include/v8\.h -in the Node source tree)\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'libev, C event loop library\. Anytime one needs to wait for a file descriptor to become readable, wait for a timer, or wait for a signal to received one will need to interface with libev\. That is, if you perform any I/O, libev will need to be used\. Node uses the -EV_DEFAULT -event loop\. Documentation can be found -here\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'libeio, C thread pool library\. Used to execute blocking POSIX system calls asynchronously\. Mostly wrappers already exist for such calls, in -src/file\.cc -so you will probably not need to use it\. If you do need it, look at the header file -deps/libeio/eio\.h\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'Internal Node libraries\. Most importantly is the -node::EventEmitter -class which you will likely want to derive from\. -.RE -.sp -.RS 4 -\h'-04'\(bu\h'+03'Others\. Look in -deps/ -for what else is available\. -.RE -Node statically compiles all its dependencies into the executable\. When compiling your module, you don\(cqt need to worry about linking to any of these libraries\. -.sp -Here is a sample Makefile taken from node_postgres: -.sp -.sp -.RS 4 -.nf -binding\.node: binding\.o Makefile - gcc \-shared \-o binding\.node binding\.o \e - \-L`pg_config \-\-libdir` \-lpq - -binding\.o: binding\.cc Makefile - gcc `node \-\-cflags` \-I`pg_config \-\-includedir` \e - binding\.cc \-c \-o binding\.o - -clean: - rm \-f binding\.o binding\.node -\.PHONY: clean -.fi -.RE -As you can see, the only thing your module needs to know about Node is the CFLAGS that node was compiled with which are gotten from node \-\-cflags If you want to make a debug build, then use node_g \-\-cflags\. (node_g is the debug build of node, which can built with configure \-\-debug; make; make install\.) -.sp -Node extension modules are dynamically linked libraries with a \.node extension\. Node opens this file and looks for a function called init() which must be of the form: -.sp -.sp -.RS 4 -.nf -extern "C" void init (Handle target) -.fi -.RE -In this function you can create new javascript objects and attach them to target\. Here is a very simple module: -.sp -.sp -.RS 4 -.nf -extern "C" void -init (Handle target) -{ - HandleScope scope; - target\->Set(String::New("hello"), String::New("World")); -} -.fi -.RE -Further documentation will come soon\. For now see the source code of node_postgres\. -.sp -.SH "NOTES" -.IP " 1." 4 -here -.RS 4 -\%http:/cvs.schmorp.de/libev/ev.html -.RE -.IP " 2." 4 -node_postgres -.RS 4 -\%http://github.com/ry/node_postgres -.RE diff --git a/wscript b/wscript index 00c529befa..3cd65f9bac 100644 --- a/wscript +++ b/wscript @@ -180,7 +180,7 @@ def build_udns(bld): #debug.target = join(debug_dir, static_lib) bld.env_of_name('debug')["STATICLIB_UDNS"] = "udns" bld.env_of_name('debug')["LIBPATH_UDNS"] = debug_dir - bld.install_files('${PREFIX}/include/node/', 'deps/udns/udns.h'); + bld.install_files('${PREFIX}/include/node/', 'deps/udns/udns.h') # XXX Remove this when v8 defaults x86_64 to native builds def GuessArchitecture(): @@ -237,7 +237,7 @@ def build_v8(bld): v8_debug.rule = v8rule % (v8dir_tgt, scons, "debug", arch) v8_debug.target = join("deps/v8", bld.env["staticlib_PATTERN"] % "v8_g") - bld.install_files('${PREFIX}/include/node/', 'deps/v8/include/v8*'); + bld.install_files('${PREFIX}/include/node/', 'deps/v8/include/v8*') def build(bld): bld.add_subdirs('deps/libeio deps/libev') @@ -255,7 +255,7 @@ def build(bld): evcom.install_path = None if bld.env["USE_DEBUG"]: evcom.clone("debug") - bld.install_files('${PREFIX}/include/node/', 'deps/evcom/evcom.h'); + bld.install_files('${PREFIX}/include/node/', 'deps/evcom/evcom.h') ### http_parser http_parser = bld.new_task_gen("cc", "staticlib") @@ -338,7 +338,7 @@ def build(bld): , 'VERSION' : VERSION , 'PREFIX' : program.env["PREFIX"] } - return x; + return x # process file.pc.in -> file.pc pkgconfig = bld.new_task_gen('subst', before="cxx") @@ -369,12 +369,17 @@ def build(bld): src/object_wrap.h src/events.h src/net.h - """); - bld.install_files('${PREFIX}/share/man/man1/', 'doc/node.1'); - bld.install_files('${PREFIX}/bin/', 'bin/*', chmod=0755); + """) + + # Only install the man page if it exists. + # Do 'make doc install' to build and install it. + if os.path.exists('doc/node.1'): + bld.install_files('${PREFIX}/share/man/man1/', 'doc/node.1') + + bld.install_files('${PREFIX}/bin/', 'bin/*', chmod=0755) # Why am I using two lines? Because WAF SUCKS. - bld.install_files('${PREFIX}/lib/node/wafadmin', 'tools/wafadmin/*.py'); - bld.install_files('${PREFIX}/lib/node/wafadmin/Tools', 'tools/wafadmin/Tools/*.py'); + bld.install_files('${PREFIX}/lib/node/wafadmin', 'tools/wafadmin/*.py') + bld.install_files('${PREFIX}/lib/node/wafadmin/Tools', 'tools/wafadmin/Tools/*.py') - bld.install_files('${PREFIX}/lib/node/libraries/', 'lib/*.js'); + bld.install_files('${PREFIX}/lib/node/libraries/', 'lib/*.js')