This commit is contained in:
Matt Ranney 2010-03-28 00:41:58 -07:00 коммит произвёл Ryan Dahl
Родитель 40ea061c30
Коммит 7c77a56b4a
1 изменённых файлов: 243 добавлений и 109 удалений

Просмотреть файл

@ -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,8 +147,60 @@ This will generate:
2: one
3: two=three
4: four
Note that `process.argv` and `process.ARGV` are equivalent.
### process.env
### process.chdir(directory)
Changes the current working directory of the process or throws an exception if that fails.
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.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.
Example of using `process.compile` and `eval` to run the same code:
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);
// localVar: 123, compiled: 1
// localVar: 1, evaled: 1
`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.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).
@ -133,6 +211,107 @@ An object containing the user environment. See environ(7).
sys.puts(index + ": " + val + "=" + process.env[val]);
});
Note that `process.env` and `process.ENV` are equivalent.
### process.evalcx(code, sandbox, filename)
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.
var sys = require("sys"),
sandbox = {
animal: "cat",
count: 2
};
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.exit(code)
Ends the process with the specified `code`. If omitted, exit uses the
"success" code `0`.
To exit with a "failure" code:
process.exit(1);
The shell that executed node should see the exit code as 1.
### process.getgid(), process.setgid(id)
Gets/sets the group identity of the process. (See setgid(2).) This is the numerical group id, not the group name.
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)
Gets/sets the user identity of the process. (See setuid(2).) This is the numerical userid, not the username.
var sys = require('sys');
sys.puts("Current uid: " + process.getuid());
try {
process.setuid(501);
sys.puts("New uid: " + process.getuid());
}
catch (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
@ -166,6 +345,7 @@ This will generate:
`heapTotal` and `heapUsed` refer to V8's memory usage.
### process.nextTick(callback)
On the next loop around the event loop call this callback.
@ -179,73 +359,6 @@ efficient.
});
### process.exit(code=0)
Ends the process with the specified code. By default it exits with the
success code 0.
To exit with
process.exit(1);
The shell that executed node should see the exit code as 1.
### process.cwd()
Returns the current working directory of the process.
require('sys').puts("Current directory: " + process.cwd());
### process.getuid(), process.setuid(id)
Gets/sets the user identity of the process. (See setuid(2).) This is the numerical userid, not the username.
var sys = require('sys');
sys.puts("Current uid: " + process.getuid());
try {
process.setuid(501);
sys.puts("New uid: " + process.getuid());
}
catch (err) {
sys.puts("Failed to set uid: " + err);
}
### process.getgid(), process.setgid(id)
Gets/sets the group identity of the process. (See setgid(2).) This is the numerical group id, not the group name.
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.chdir(directory)
Changes the current working directory of the process or throws an exception if that fails.
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.umask(mask)
Sets or read the process's file mode creation mask. Child processes inherit
@ -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.
Write data to stdout.
- **`"close"`** - `callback()`:
Emitted when stdin has been closed.
### process.stdio.writeError(data)
Write data to stderr. Synchronous.
Example of opening standard input and listening for both events:
### process.stdio.close()
var sys = require("sys"),
stdin = process.openStdin();
stdin.addListener("data", function (chunk) {
sys.print("data: " + chunk);
});
stdin.addListener("end", function () {
sys.puts("end");
});
Close stdin.
## MODULES