diff --git a/doc/api.markdown b/doc/api.markdown index 2d342f45fb..39d625063c 100644 --- a/doc/api.markdown +++ b/doc/api.markdown @@ -8,6 +8,7 @@ World": var sys = require("sys"), http = require("http"); + http.createServer(function (request, response) { response.writeHead(200, { "Content-Type": "text/plain" @@ -15,6 +16,7 @@ World": response.write("Hello World\n"); response.close(); }).listen(8000); + sys.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 @@ -25,6 +27,7 @@ it with the node program All of the examples in the documentation can be run similarly. + ## ENCODINGS Node supports 3 string encodings. UTF-8 (`"utf8"`), ASCII (`"ascii"`), and @@ -55,15 +58,14 @@ object" section. ## PROCESS OBJECT -The `process` object is an instance of `EventEmitter` and has the following events: +The `process` object is a global object and can be accessed from anywhere. +It is an instance of `EventEmitter` and has the following events: - - **`"exit"`** - `callback(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 a - 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()`. + - **`"exit"`** - `callback()`: + Made when the process is about to exit. + This is a good hook to perform constant time checks of the module's state (like for unit tests). + The main event loop will no longer be run after the "exit" callback finishes, so timers may not + be scheduled. - **`"uncaughtException"`** - `callback(exception)`: Emitted when an exception bubbles all the way back to the event loop. If a @@ -74,6 +76,18 @@ The `process` object is an instance of `EventEmitter` and has the following even Emitted when the processes receives a signal. See sigaction(2) for a list of standard POSIX signal names such as SIGINT, SIGUSR1, etc. +Example of listening for `exit`: + + var sys = require('sys'); + + process.addListener("exit", function () { + process.nextTick(function () { + sys.puts("This will not run"); + }); + + sys.puts("About to exit."); + }); + Example of listening for `uncaughtException`: @@ -100,8 +114,20 @@ try / catch in your program will give you more control over your program's flow. Especially for server programs that are designed to stay running forever, `uncaughtException` can be a useful safety mechanism. + +Example of listening for `SIGINT`: + + var sys = require("sys"), + stdin = process.openStdin(); + + process.addListener("SIGINT", function () { + sys.puts("Got SIGINT. Press Control-D to exit."); + }); + +An easy way to send the `SIGINT` signal is with `Control-C` in most terminal programs. + -### process.argv +### process.argv, process.ARGV An array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments. @@ -121,81 +147,120 @@ This will generate: 2: one 3: two=three 4: four + +Note that `process.argv` and `process.ARGV` are equivalent. -### process.env -An object containing the user environment. See environ(7). +### process.chdir(directory) - // print process.env - var sys = require("sys"); +Changes the current working directory of the process or throws an exception if that fails. - Object.getOwnPropertyNames(process.env).forEach(function (val, index, array) { - sys.puts(index + ": " + val + "=" + process.env[val]); - }); + var sys = require('sys'); + sys.puts("Starting directory: " + process.cwd()); + try { + process.chdir("/tmp"); + sys.puts("New directory: " + process.cwd()); + } + catch (err) { + sys.puts("chdir: " + err); + } -### process.pid -The PID of the process. +### process.compile(code, filename) - require("sys").puts("This process is pid " + process.pid); +Similar to `eval` except that you can specify a `filename` for better +error reporting and the `code` cannot see the local scope. The value of `filename` +will be used as a filename if a stack trace is generated by the compiled code. +Example of using `process.compile` and `eval` to run the same code: -### process.platform + var sys = require("sys"), + localVar = 123, + compiled, evaled; + + compiled = process.compile("localVar = 1;", "myfile.js"); + sys.puts("localVar: " + localVar + ", compiled: " + compiled); + evaled = eval("localVar = 1;"); + sys.puts("localVar: " + localVar + ", evaled: " + evaled); -What platform you're running on. `"linux2"`, `"darwin"`, etc. + // localVar: 123, compiled: 1 + // localVar: 1, evaled: 1 - require("sys").puts("This platform is " + process.platform); +`process.compile` does not have access to the local scope, so `localVar` is unchanged. +`eval` does have access to the local scope, so `localVar` is changed. +See also: `process.evalcx` -### process.memoryUsage() -Returns an object describing the memory usage of the Node process. +### process.cwd() + +Returns the current working directory of the process. + + require('sys').puts("Current directory: " + process.cwd()); + +### process.env, process.ENV + +An object containing the user environment. See environ(7). + + // print process.env var sys = require("sys"); - sys.puts(sys.inspect(process.memoryUsage())); + Object.getOwnPropertyNames(process.env).forEach(function (val, index, array) { + sys.puts(index + ": " + val + "=" + process.env[val]); + }); -This will generate: +Note that `process.env` and `process.ENV` are equivalent. - { rss: 4935680 - , vsize: 41893888 - , heapTotal: 1826816 - , heapUsed: 650472 - } -`heapTotal` and `heapUsed` refer to V8's memory usage. +### process.evalcx(code, sandbox, filename) -### process.nextTick(callback) +Similar to `eval` and `process.compile`. `process.evalcx` compiles `code` to run in `sandbox` +as if it were loaded from `filename`. The object `sandbox` will be used as the global object for +`code`. `sandbox` and `filename` are optional. -On the next loop around the event loop call this callback. -This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more -efficient. + var sys = require("sys"), + sandbox = { + animal: "cat", + count: 2 + }; + + process.evalcx('count += 1; name = "kitty"', sandbox, "myfile.js"); + sys.puts(sys.inspect(sandbox)); - var sys = require("sys"); +Note that running untrusted code is a tricky business requiring great care. To prevent accidental +global variable leakage, `process.evalcx` is quite useful, but to safely run untrusted code, many more steps +must be taken. - process.nextTick(function () { - sys.puts("nextTick callback"); - }); -### process.exit(code=0) +### process.exit(code) -Ends the process with the specified code. By default it exits with the -success code 0. +Ends the process with the specified `code`. If omitted, exit uses the +"success" code `0`. -To exit with +To exit with a "failure" code: process.exit(1); The shell that executed node should see the exit code as 1. -### process.cwd() +### process.getgid(), process.setgid(id) -Returns the current working directory of the process. +Gets/sets the group identity of the process. (See setgid(2).) This is the numerical group id, not the group name. - require('sys').puts("Current directory: " + process.cwd()); + var sys = require('sys'); + + sys.puts("Current gid: " + process.getgid()); + try { + process.setgid(501); + sys.puts("New gid: " + process.getgid()); + } + catch (err) { + sys.puts("Failed to set gid: " + err); + } ### process.getuid(), process.setuid(id) @@ -214,37 +279,85 @@ Gets/sets the user identity of the process. (See setuid(2).) This is the numeri } -### process.getgid(), process.setgid(id) +### process.installPrefix -Gets/sets the group identity of the process. (See setgid(2).) This is the numerical group id, not the group name. +A compiled-in property that exposes `NODE_PREFIX`. - var sys = require('sys'); + require("sys").puts("Install prefix: " + process.installPrefix); - sys.puts("Current gid: " + process.getgid()); - try { - process.setgid(501); - sys.puts("New gid: " + process.getgid()); - } - catch (err) { - sys.puts("Failed to set gid: " + err); - } +### process.kill(pid, signal) -### process.chdir(directory) +Send a signal to a process. `pid` is the process id and `signal` is the +string describing the signal to send. Signal names are strings like +"SIGINT" or "SIGUSR1". If omitted, the signal will be "SIGINT". +See kill(2) for more information. -Changes the current working directory of the process or throws an exception if that fails. +Note that just because the name of this function is `process.kill`, it is +really just a signal sender, like the `kill` system call. The signal sent +may do something other than kill the target process. - var sys = require('sys'); +Example of sending a signal to yourself: - sys.puts("Starting directory: " + process.cwd()); - try { - process.chdir("/tmp"); - sys.puts("New directory: " + process.cwd()); - } - catch (err) { - sys.puts("chdir: " + err); + var sys = require("sys"); + + process.addListener("SIGHUP", function () { + sys.puts("Got SIGHUP signal."); + }); + + setTimeout(function () { + sys.puts("Exiting."); + process.exit(0); + }, 100); + + process.kill(process.pid, "SIGHUP"); + + +### process.pid + +The PID of the process. + + require("sys").puts("This process is pid " + process.pid); + + +### process.platform + +What platform you're running on. `"linux2"`, `"darwin"`, etc. + + require("sys").puts("This platform is " + process.platform); + + +### process.memoryUsage() + +Returns an object describing the memory usage of the Node process. + + var sys = require("sys"); + + sys.puts(sys.inspect(process.memoryUsage())); + +This will generate: + + { rss: 4935680 + , vsize: 41893888 + , heapTotal: 1826816 + , heapUsed: 650472 } +`heapTotal` and `heapUsed` refer to V8's memory usage. + + +### process.nextTick(callback) + +On the next loop around the event loop call this callback. +This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more +efficient. + + var sys = require("sys"); + + process.nextTick(function () { + sys.puts("nextTick callback"); + }); + ### process.umask(mask) @@ -260,42 +373,45 @@ given, otherwise returns the current mask. sys.puts("Changed umask from: " + oldmask + " to " + newmask); -### process.kill(pid, signal="SIGTERM") - -Send a signal to a process. `pid` is the process id and `signal` is the -signal to send; for example, "SIGINT" or "SIGUSR1". See kill(2) for more -information. - -### process.compile(source, scriptOrigin) - -Similar to `eval()` except that you can specify a `scriptOrigin` for better -error reporting and the `code` cannot see the local scope. ## SYSTEM MODULE These functions are in the module `"sys"`. Use `require("sys")` to access them. + ### puts(string) Outputs `string` and a trailing new-line to `stdout`. + require("sys").puts("String with a newline"); + + ### print(string) Like `puts()` but without the trailing new-line. + require("sys").print("String with no newline"); + + ### debug(string) A synchronous output function. Will block the process and -output `string` immediately to `stdout`. +output `string` immediately to `stderr`. + + require("sys").debug("message on stderr"); + ### log(string) -Output with timestamp. +Output with timestamp on `stdout`. + + require("sys").log("Timestmaped message."); + ### inspect(object, showHidden, depth) -Return a string representation of `object`. (For debugging.) +Return a string representation of `object`, which is useful for debugging. If `showHidden` is `true`, then the object's non-enumerable properties will be shown too. @@ -306,6 +422,14 @@ formatting the object. This is useful for inspecting large complicated objects. The default is to only recurse twice. To make it recurse indefinitely, pass in `null` for `depth`. +Example of inspecting all properties of the `sys` object: + + var sys = require("sys"); + + sys.puts(sys.inspect(sys, true, null)); + + + ## EVENTS Many objects in Node emit events: a TCP server emits an event each time @@ -318,6 +442,7 @@ Events are represented by a camel-cased string. Here are some examples: Functions can be then be attached to objects, to be executed when an event is emitted. These functions are called _listeners_. + ### events.EventEmitter `require("events")` to access the events module. @@ -325,8 +450,9 @@ is emitted. These functions are called _listeners_. All EventEmitters emit the event `"newListener"` when new listeners are added. - - **`"newListener"`** - `callback(event, listener)`: - This event is made any time someone adds a new listener. +- **`"newListener"`** - `callback(event, listener)`: +This event is made any time someone adds a new listener. + ### emitter.addListener(event, listener) @@ -336,55 +462,63 @@ Adds a listener to the end of the listeners array for the specified event. sys.puts("someone connected!"); }); + ### emitter.removeListener(event, listener) Remove a listener from the listener array for the specified event. **Caution**: changes array indices in the listener array behind the listener. + ### emitter.removeAllListeners(event) Removes all listeners from the listener array for the specified event. + ### 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. + ## STANDARD I/O -Standard I/O is handled through a special object `process.stdio`. `stdout` and -`stdin` are fully non-blocking (even when piping to files). `stderr` is -synchronous. +Writing data to standard output is typically done with the output functions in the `sys` module. - - **`"data"`** - `callback(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 `process.stdio.open()` has been called. +The underlying `net.Stream` object associated with `stdout` and `stdin` is available via `process.stdout` +and `process.stdin`. To read from standard input, it must first be opened. See below. - - **`"close"`** - `callback()`: - Made when stdin has been closed. -### process.stdio.open(encoding="utf8") +### process.openStdin() -Open stdin. The program will not exit until `process.stdio.close()` has been +Open stdin. The program will not exit until `process.stdin.close()` has been called or the `"close"` event has been emitted. -### process.stdio.write(data) +- **`"data"`** - `callback(data)`: +Emitted when stdin has received a chunk of data. + +- **`"close"`** - `callback()`: +Emitted when stdin has been closed. + -Write data to stdout. +Example of opening standard input and listening for both events: -### process.stdio.writeError(data) + var sys = require("sys"), + stdin = process.openStdin(); -Write data to stderr. Synchronous. + stdin.addListener("data", function (chunk) { + sys.print("data: " + chunk); + }); -### process.stdio.close() + stdin.addListener("end", function () { + sys.puts("end"); + }); -Close stdin. ## MODULES