Browse Source

Improve documentation.

v0.7.4-release
Matt Ranney 15 years ago
committed by Ryan Dahl
parent
commit
7c77a56b4a
  1. 330
      doc/api.markdown

330
doc/api.markdown

@ -8,6 +8,7 @@ World":
var sys = require("sys"), var sys = require("sys"),
http = require("http"); http = require("http");
http.createServer(function (request, response) { http.createServer(function (request, response) {
response.writeHead(200, { response.writeHead(200, {
"Content-Type": "text/plain" "Content-Type": "text/plain"
@ -15,6 +16,7 @@ World":
response.write("Hello World\n"); response.write("Hello World\n");
response.close(); response.close();
}).listen(8000); }).listen(8000);
sys.puts("Server running at http://127.0.0.1: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 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. All of the examples in the documentation can be run similarly.
## ENCODINGS ## ENCODINGS
Node supports 3 string encodings. UTF-8 (`"utf8"`), ASCII (`"ascii"`), and Node supports 3 string encodings. UTF-8 (`"utf8"`), ASCII (`"ascii"`), and
@ -55,15 +58,14 @@ object" section.
## PROCESS OBJECT ## 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)`: - **`"uncaughtException"`** - `callback(exception)`:
Emitted when an exception bubbles all the way back to the event loop. If a 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 Emitted when the processes receives a signal. See sigaction(2) for a list
of standard POSIX signal names such as SIGINT, SIGUSR1, etc. 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`: Example of listening for `uncaughtException`:
@ -101,7 +115,19 @@ Especially for server programs that are designed to stay running forever, `uncau
can be a useful safety mechanism. can be a useful safety mechanism.
### process.argv 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
An array containing the command line arguments. The first element will be 'node', the second element 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. will be the name of the JavaScript file. The next elements will be any additional command line arguments.
@ -122,96 +148,103 @@ This will generate:
3: two=three 3: two=three
4: four 4: four
### process.env Note that `process.argv` and `process.ARGV` are equivalent.
An object containing the user environment. See environ(7).
// print process.env ### process.chdir(directory)
var sys = require("sys");
Object.getOwnPropertyNames(process.env).forEach(function (val, index, array) { Changes the current working directory of the process or throws an exception if that fails.
sys.puts(index + ": " + val + "=" + process.env[val]);
});
var sys = require('sys');
### process.pid sys.puts("Starting directory: " + process.cwd());
try {
process.chdir("/tmp");
sys.puts("New directory: " + process.cwd());
}
catch (err) {
sys.puts("chdir: " + err);
}
The PID of the process.
require("sys").puts("This process is pid " + process.pid); ### process.compile(code, filename)
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.
### process.platform Example of using `process.compile` and `eval` to run the same code:
What platform you're running on. `"linux2"`, `"darwin"`, etc. var sys = require("sys"),
localVar = 123,
compiled, evaled;
require("sys").puts("This platform is " + process.platform); compiled = process.compile("localVar = 1;", "myfile.js");
sys.puts("localVar: " + localVar + ", compiled: " + compiled);
evaled = eval("localVar = 1;");
sys.puts("localVar: " + localVar + ", evaled: " + evaled);
// localVar: 123, compiled: 1
// localVar: 1, evaled: 1
### process.memoryUsage() `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.
Returns an object describing the memory usage of the Node process. See also: `process.evalcx`
var sys = require("sys");
sys.puts(sys.inspect(process.memoryUsage())); ### process.cwd()
This will generate: Returns the current working directory of the process.
{ rss: 4935680 require('sys').puts("Current directory: " + process.cwd());
, vsize: 41893888
, heapTotal: 1826816
, heapUsed: 650472
}
`heapTotal` and `heapUsed` refer to V8's memory usage.
### process.nextTick(callback) ### process.env, process.ENV
On the next loop around the event loop call this callback. An object containing the user environment. See environ(7).
This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more
efficient.
// print process.env
var sys = require("sys"); var sys = require("sys");
process.nextTick(function () { Object.getOwnPropertyNames(process.env).forEach(function (val, index, array) {
sys.puts("nextTick callback"); sys.puts(index + ": " + val + "=" + process.env[val]);
}); });
Note that `process.env` and `process.ENV` are equivalent.
### process.exit(code=0)
Ends the process with the specified code. By default it exits with the ### process.evalcx(code, sandbox, filename)
success code 0.
To exit with 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.
process.exit(1); var sys = require("sys"),
sandbox = {
animal: "cat",
count: 2
};
The shell that executed node should see the exit code as 1. process.evalcx('count += 1; name = "kitty"', sandbox, "myfile.js");
sys.puts(sys.inspect(sandbox));
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.cwd()
Returns the current working directory of the process.
require('sys').puts("Current directory: " + process.cwd()); ### process.exit(code)
Ends the process with the specified `code`. If omitted, exit uses the
"success" code `0`.
### process.getuid(), process.setuid(id) To exit with a "failure" code:
Gets/sets the user identity of the process. (See setuid(2).) This is the numerical userid, not the username. process.exit(1);
var sys = require('sys');
sys.puts("Current uid: " + process.getuid()); The shell that executed node should see the exit code as 1.
try {
process.setuid(501);
sys.puts("New uid: " + process.getuid());
}
catch (err) {
sys.puts("Failed to set uid: " + err);
}
### process.getgid(), process.setgid(id) ### process.getgid(), process.setgid(id)
@ -230,21 +263,101 @@ Gets/sets the group identity of the process. (See setgid(2).) This is the numer
} }
### process.chdir(directory) ### process.getuid(), process.setuid(id)
Changes the current working directory of the process or throws an exception if that fails. Gets/sets the user identity of the process. (See setuid(2).) This is the numerical userid, not the username.
var sys = require('sys'); var sys = require('sys');
sys.puts("Starting directory: " + process.cwd()); sys.puts("Current uid: " + process.getuid());
try { try {
process.chdir("/tmp"); process.setuid(501);
sys.puts("New directory: " + process.cwd()); sys.puts("New uid: " + process.getuid());
} }
catch (err) { catch (err) {
sys.puts("chdir: " + err); sys.puts("Failed to set uid: " + err);
}
### process.installPrefix
A compiled-in property that exposes `NODE_PREFIX`.
require("sys").puts("Install prefix: " + process.installPrefix);
### process.kill(pid, signal)
Send a signal to a process. `pid` is the process id and `signal` is the
string describing the signal to send. Signal names are strings like
"SIGINT" or "SIGUSR1". If omitted, the signal will be "SIGINT".
See kill(2) for more information.
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.
Example of sending a signal to yourself:
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) ### process.umask(mask)
@ -260,42 +373,45 @@ given, otherwise returns the current mask.
sys.puts("Changed umask from: " + oldmask + " to " + newmask); 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 ## SYSTEM MODULE
These functions are in the module `"sys"`. Use `require("sys")` to access These functions are in the module `"sys"`. Use `require("sys")` to access
them. them.
### puts(string) ### puts(string)
Outputs `string` and a trailing new-line to `stdout`. Outputs `string` and a trailing new-line to `stdout`.
require("sys").puts("String with a newline");
### print(string) ### print(string)
Like `puts()` but without the trailing new-line. Like `puts()` but without the trailing new-line.
require("sys").print("String with no newline");
### debug(string) ### debug(string)
A synchronous output function. Will block the process and 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) ### log(string)
Output with timestamp. Output with timestamp on `stdout`.
require("sys").log("Timestmaped message.");
### inspect(object, showHidden, depth) ### 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 If `showHidden` is `true`, then the object's non-enumerable properties will be
shown too. 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 The default is to only recurse twice. To make it recurse indefinitely, pass
in `null` for `depth`. 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 ## EVENTS
Many objects in Node emit events: a TCP server emits an event each time 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 Functions can be then be attached to objects, to be executed when an event
is emitted. These functions are called _listeners_. is emitted. These functions are called _listeners_.
### events.EventEmitter ### events.EventEmitter
`require("events")` to access the events module. `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 All EventEmitters emit the event `"newListener"` when new listeners are
added. added.
- **`"newListener"`** - `callback(event, listener)`: - **`"newListener"`** - `callback(event, listener)`:
This event is made any time someone adds a new listener. This event is made any time someone adds a new listener.
### emitter.addListener(event, 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!"); sys.puts("someone connected!");
}); });
### emitter.removeListener(event, listener) ### emitter.removeListener(event, listener)
Remove a listener from the listener array for the specified event. Remove a listener from the listener array for the specified event.
**Caution**: changes array indices in the listener array behind the listener. **Caution**: changes array indices in the listener array behind the listener.
### emitter.removeAllListeners(event) ### emitter.removeAllListeners(event)
Removes all listeners from the listener array for the specified event. Removes all listeners from the listener array for the specified event.
### emitter.listeners(event) ### emitter.listeners(event)
Returns an array of listeners for the specified event. This array can be Returns an array of listeners for the specified event. This array can be
manipulated, e.g. to remove listeners. manipulated, e.g. to remove listeners.
### emitter.emit(event, arg1, arg2, ...) ### emitter.emit(event, arg1, arg2, ...)
Execute each of the listeners in order with the supplied arguments. Execute each of the listeners in order with the supplied arguments.
## STANDARD I/O ## STANDARD I/O
Standard I/O is handled through a special object `process.stdio`. `stdout` and Writing data to standard output is typically done with the output functions in the `sys` module.
`stdin` are fully non-blocking (even when piping to files). `stderr` is
synchronous.
- **`"data"`** - `callback(data)`: The underlying `net.Stream` object associated with `stdout` and `stdin` is available via `process.stdout`
Made when stdin has received a chunk of data. Depending on the encoding that and `process.stdin`. To read from standard input, it must first be opened. See below.
stdin was opened with, `data` will be a string. This event will only be
emited after `process.stdio.open()` has been called.
- **`"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. 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 ## MODULES

Loading…
Cancel
Save