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\.
Returns the current working directory of the process\.
.RE
.SS"Global Variables"
.PP
ARGV
.RS4
An array containing the command line arguments\.
.RE
.PP
ENV
.RS4
An object containing the user environment\. See environ(7)\.
.RE
.PP
__filename
.RS4
The filename of the script being executed\.
.RE
.PP
process
.RS4
A special global object\. The
process
object is like the
window
object of browser\-side javascript\.
.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 snakecased string\. Here are some examples: "connection", "receive", "message_begin"\.
.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
.it1an-trap
.nran-no-space-flag1
.nran-break-flag1
.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)
.RS4
Adds a listener to the end of the listeners array for the specified event\.
.sp
.RS4
.nf
server\.addListener("connection", function (socket) {
puts("someone connected!");
});
.fi
.RE
.RE
.PP
emitter\.listeners(event)
.RS4
Returns an array of listeners for the specified event\. This array can be manipulated, e\.g\. to remove listeners\.
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\.
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\.
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\.
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 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\.
.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
HTTP URLs can also be used to load modules\. For example,
.sp
.sp
.RS4
.nf
var circle = require("http://tinyclouds\.org/node/circle\.js");
.fi
.RE
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
.RS4
.nf
include("circle\.js");
puts("The area of a cirlce of radius 4 is " + area(4));
.fi
.RE
Functions require_async() and include_async() also exist\.
.sp
.sp
.it1an-trap
.nran-no-space-flag1
.nran-break-flag1
.br
process.addListener("exit", function () { })
.RS
When the program exits a special object called process will emit an "exit" event\.
The "exit" event cannot perform I/O since the process is going to forcibly exit in less than microsecond\. However, it is a good hook to perform constant time checks of the module\(cqs state\. E\.G\. for unit tests:
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\.
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\.
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)
.RS4
Launches a new process with the given
command\. For example:
.sp
.RS4
.nf
var ls = node\.createChildProcess("ls \-lh /usr");
ls\.addListener("output", function (data) {
puts(data);
});
.fi
.RE
.RE
.PP
child\.pid
.RS4
The PID of the child process\.
.RE
.PP
child\.write(data, encoding="ascii")
.RS4
Write data to the child process\(cqs
stdin\. The second argument is optional and specifies the encoding: possible values are
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
.RS4
.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
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
.RS4
.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\. That means, for example, that Node does not, and will never, provide API to access or manipulate Cookies or multi\-part bodies\.\fIThis is left to the user\.\fR
.sp
.sp
.it1an-trap
.nran-no-space-flag1
.nran-break-flag1
.br
node.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 node\.http\.ServerRequest response is an instance of node\.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 node\.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\.
argument accepts the same values as the options argument for
node\.tcp\.Server
does\.
.sp
The
request_listener
is a function which is automatically added to the
"request"
event\.
.RE
.PP
server\.listen(port, hostname)
.RS4
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()
.RS4
Stops the server from accepting new connections\.
.RE
.RE
.sp
.it1an-trap
.nran-no-space-flag1
.nran-break-flag1
.br
node.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\.
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()\.
Pauses request from emitting events\. Useful to throttle back an upload\.
.RE
.PP
request\.resume()
.RS4
Resumes a paused request\.
.RE
.PP
request\.connection
.RS4
The
node\.http\.Connection
object\.
.RE
.RE
.sp
.it1an-trap
.nran-no-space-flag1
.nran-break-flag1
.br
node.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)
.RS4
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
.RS4
.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")
.RS4
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()
.RS4
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
.it1an-trap
.nran-no-space-flag1
.nran-break-flag1
.br
node.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
.RS4
.nf
var google = node\.http\.createClient(80, "google\.com");
Issues a request; if necessary establishes connection\. Returns a
node\.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
.it1an-trap
.nran-no-space-flag1
.nran-break-flag1
.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
.it1an-trap
.nran-no-space-flag1
.nran-break-flag1
.br
node.http.ClientRequest
.RS
This object is created internally and returned from the request methods of a node\.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 node\.http\.ClientResponse\.
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
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
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
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()\.
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\.
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\.)
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")
.RS4
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
.RS4
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\.
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\.
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)
.RS4
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
.RS4
\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
.RS4
\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)
.RS4
The same as
node\.dns\.resolve4()
except for IPv6 queries (an
AAAA
query)\.
.RE
.PP
node\.dns\.reverse(ip)
.RS4
Reverse resolves an ip address to an array of domain names\.
.sp
.RS4
\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
.RS4
\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
.RS4
\h'-04'\(bu\h'+03'
node\.dns\.TEMPFAIL: timeout, SERVFAIL or similar\.
.RE
.sp
.RS4
\h'-04'\(bu\h'+03'
node\.dns\.PROTOCOL: got garbled reply\.
.RE
.sp
.RS4
\h'-04'\(bu\h'+03'
node\.dns\.NXDOMAIN: domain does not exists\.
.RE
.sp
.RS4
\h'-04'\(bu\h'+03'
node\.dns\.NODATA: domain exists but no data of reqd type\.
.RE
.sp
.RS4
\h'-04'\(bu\h'+03'
node\.dns\.NOMEM: out of memory while processing\.
.RE
.sp
.RS4
\h'-04'\(bu\h'+03'
node\.dns\.BADQUERY: the query is malformed\.
.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
.RS4
\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
.RS4
\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
.RS4
\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
.RS4
\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
.RS4
\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:
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
.RS4
.nf
extern "C" void init (Handle<Object> target)
.fi
.RE
In this function you can create new javascript objects and attach them to target\. Here is a very simple module: