262
252
.SH "EventEmitter"
263
253
Many objects in Node emit events: a TCP server emits an event each time
264
there is a stream, a child process emits an event when it exits. All
265
objects which emit events are instances of \fBevents.EventEmitter\fR.
254
there is a stream, a child process emits an event when it exits\. All
255
objects which emit events are instances of \fBevents\.EventEmitter\fR\|\.
268
Events are represented by a camel\-cased string. Here are some examples:\fB'stream'\fR, \fB'data'\fR, \fB'messageBegin'\fR.
258
Events are represented by a camel\-cased string\. Here are some examples: \fB\'stream\'\fR, \fB\'data\'\fR, \fB\'messageBegin\'\fR\|\.
271
261
Functions can be then be attached to objects, to be executed when an event
272
is emitted. These functions are called \fIlisteners\fR.
275
\fBrequire('events').EventEmitter\fR to access the \fBEventEmitter\fR class.
278
All EventEmitters emit the event \fB'newListener'\fR when new listeners are
282
When an EventEmitter experiences an error, the typical action is to emit an\fB'error'\fR event. Error events are special\-\-if there is no handler for them
283
they will print a stack trace and exit the program.
285
.SS "Event: 'newListener'"
262
is emitted\. These functions are called \fIlisteners\fR\|\.
265
\fBrequire(\'events\')\.EventEmitter\fR to access the \fBEventEmitter\fR class\.
268
All EventEmitters emit the event \fB\'newListener\'\fR when new listeners are
272
When an \fBEventEmitter\fR experiences an error, the typical action is to emit an \fB\'error\'\fR event\. Error events are special\-\-if there is no handler for them
273
they will print a stack trace and exit the program\.
275
.SS "Event: \'newListener\'"
286
276
\fBfunction (event, listener) { }\fR
289
This event is made any time someone adds a new listener.
279
This event is emitted any time someone adds a new listener\.
281
.SS "Event: \'error\'"
292
282
\fBfunction (exception) { }\fR
295
If an error was encountered, then this event is emitted. This event is
285
If an error was encountered, then this event is emitted\. This event is
296
286
special \- when there are no listeners to receive the error Node will
297
terminate execution and display the exception's stack trace.
299
.SS "emitter.addListener(event, listener)"
300
Adds a listener to the end of the listeners array for the specified event.
305
server.addListener('stream', function (stream) {
306
sys.puts('someone connected!');
313
.SS "emitter.removeListener(event, listener)"
314
Remove a listener from the listener array for the specified event.\fBCaution\fR: changes array indices in the listener array behind the listener.
316
.SS "emitter.removeAllListeners(event)"
317
Removes all listeners from the listener array for the specified event.
319
.SS "emitter.listeners(event)"
320
Returns an array of listeners for the specified event. This array can be
321
manipulated, e.g. to remove listeners.
323
.SS "emitter.emit(event, arg1, arg2, ...)"
324
Execute each of the listeners in order with the supplied arguments.
287
terminate execution and display the exception\'s stack trace\.
289
.SS "emitter\.on(event, listener)"
290
Adds a listener to the end of the listeners array for the specified event\.
295
server\.on(\'stream\', function (stream) {
296
console\.log(\'someone connected!\');
303
.SS "emitter\.removeListener(event, listener)"
304
Remove a listener from the listener array for the specified event\. \fBCaution\fR: changes array indices in the listener array behind the listener\.
309
var callback = function(stream) {
310
console\.log(\'someone connected!\');
312
server\.on(\'stream\', callback);
314
server\.removeListener(\'stream\', callback);
320
.SS "emitter\.removeAllListeners(event)"
321
Removes all listeners from the listener array for the specified event\.
323
.SS "emitter\.listeners(event)"
324
Returns an array of listeners for the specified event\. This array can be
325
manipulated, e\.g\. to remove listeners\.
330
server\.on(\'stream\', function (stream) {
331
console\.log(\'someone connected!\');
333
console\.log(sys\.inspect(server\.listeners(\'stream\'));
340
.SS "emitter\.emit(event, [arg1], [arg2], [\.\.\.])"
341
Execute each of the listeners in order with the supplied arguments\.
327
A stream is an abstract interface implemented by various objects in Node.
328
For example a request to an HTTP server is a stream, as is stdout. Streams
329
are readable, writable, or both. All streams are instances of \fBEventEmitter\fR.
344
A stream is an abstract interface implemented by various objects in Node\.
345
For example a request to an HTTP server is a stream, as is stdout\. Streams
346
are readable, writable, or both\. All streams are instances of \fBEventEmitter\fR\|\.
331
348
.SH "Readable Stream"
332
A \fBreadable stream\fR has the following methods, members, and events.
349
A \fBReadable Stream\fR has the following methods, members, and events\.
351
.SS "Event: \'data\'"
335
352
\fBfunction (data) { }\fR
338
The \fB'data'\fR event emits either a \fBBuffer\fR (by default) or a string if \fBsetEncoding()\fR was used.
355
The \fB\'data\'\fR event emits either a \fBBuffer\fR (by default) or a string if \fBsetEncoding()\fR was used\.
341
358
\fBfunction () { }\fR
344
Emitted when the stream has received an EOF (FIN in TCP terminology).
345
Indicates that no more \fB'data'\fR events will happen. If the stream is also
346
writable, it may be possible to continue writing.
361
Emitted when the stream has received an EOF (FIN in TCP terminology)\.
362
Indicates that no more \fB\'data\'\fR events will happen\. If the stream is also
363
writable, it may be possible to continue writing\.
365
.SS "Event: \'error\'"
349
366
\fBfunction (exception) { }\fR
352
Emitted if there was an error receiving data.
369
Emitted if there was an error receiving data\.
371
.SS "Event: \'close\'"
355
372
\fBfunction () { }\fR
358
Emitted when the underlying file descriptor has be closed. Not all streams
359
will emit this. (For example, an incoming HTTP request will not emit\fB'close'\fR.)
361
.SS "stream.setEncoding(encoding)"
362
Makes the data event emit a string instead of a \fBBuffer\fR. \fBencoding\fR can be \fB'utf8'\fR, \fB'ascii'\fR, or \fB'binary'\fR.
365
Pauses the incoming \fB'data'\fR events.
367
.SS "stream.resume()"
368
Resumes the incoming \fB'data'\fR events after a \fBpause()\fR.
370
.SS "stream.destroy()"
371
Closes the underlying file descriptor. Stream will not emit any more events.
375
Emitted when the underlying file descriptor has be closed\. Not all streams
376
will emit this\. (For example, an incoming HTTP request will not emit \fB\'close\'\fR\|\.)
379
\fBfunction (fd) { }\fR
382
Emitted when a file descriptor is received on the stream\. Only UNIX streams
383
support this functionality; all others will simply never emit this event\.
385
.SS "stream\.readable"
386
A boolean that is \fBtrue\fR by default, but turns \fBfalse\fR after an \fB\'error\'\fR
387
occured, the stream came to an \fB\'end\'\fR, or \fBdestroy()\fR was called\.
389
.SS "stream\.setEncoding(encoding)"
390
Makes the data event emit a string instead of a \fBBuffer\fR\|\. \fBencoding\fR can be \fB\'utf8\'\fR, \fB\'ascii\'\fR, or \fB\'base64\'\fR\|\.
392
.SS "stream\.pause()"
393
Pauses the incoming \fB\'data\'\fR events\.
395
.SS "stream\.resume()"
396
Resumes the incoming \fB\'data\'\fR events after a \fBpause()\fR\|\.
398
.SS "stream\.destroy()"
399
Closes the underlying file descriptor\. Stream will not emit any more events\.
373
401
.SH "Writable Stream"
374
A \fBwritable stream\fR has the following methods, members, and events.
402
A \fBWritable Stream\fR has the following methods, members, and events\.
404
.SS "Event: \'drain\'"
377
405
\fBfunction () { }\fR
380
408
Emitted after a \fBwrite()\fR method was called that returned \fBfalse\fR to
381
indicate that it is safe to write again.
409
indicate that it is safe to write again\.
411
.SS "Event: \'error\'"
384
412
\fBfunction (exception) { }\fR
387
Emitted on error with the exception \fBexception\fR.
415
Emitted on error with the exception \fBexception\fR\|\.
417
.SS "Event: \'close\'"
390
418
\fBfunction () { }\fR
393
Emitted when the underlying file descriptor has been closed.
395
.SS "stream.write(string, encoding)"
396
Writes \fBstring\fR with the given \fBencoding\fR to the stream. Returns \fBtrue\fR if
397
the string has been flushed to the kernel buffer. Returns \fBfalse\fR to
421
Emitted when the underlying file descriptor has been closed\.
423
.SS "stream\.writeable"
424
A boolean that is \fBtrue\fR by default, but turns \fBfalse\fR after an \fB\'error\'\fR
425
occurred or \fBend()\fR / \fBdestroy()\fR was called\.
427
.SS "stream\.write(string, encoding=\'utf8\', [fd])"
428
Writes \fBstring\fR with the given \fBencoding\fR to the stream\. Returns \fBtrue\fR if
429
the string has been flushed to the kernel buffer\. Returns \fBfalse\fR to
398
430
indicate that the kernel buffer is full, and the data will be sent out in
399
the future. The \fB'drain'\fR event will indicate when the kernel buffer is
400
empty again. The \fBencoding\fR defaults to \fB'utf8'\fR.
402
.SS "stream.write(buffer)"
403
Same as the above except with a raw buffer.
406
Terminates the stream with EOF or FIN.
408
.SS "stream.end(string, encoding)"
431
the future\. The \fB\'drain\'\fR event will indicate when the kernel buffer is
432
empty again\. The \fBencoding\fR defaults to \fB\'utf8\'\fR\|\.
435
If the optional \fBfd\fR parameter is specified, it is interpreted as an integral
436
file descriptor to be sent over the stream\. This is only supported for UNIX
437
streams, and is silently ignored otherwise\. When writing a file descriptor in
438
this manner, closing the descriptor before the stream drains risks sending an
439
invalid (closed) FD\.
441
.SS "stream\.write(buffer)"
442
Same as the above except with a raw buffer\.
445
Terminates the stream with EOF or FIN\.
447
.SS "stream\.end(string, encoding)"
409
448
Sends \fBstring\fR with the given \fBencoding\fR and terminates the stream with EOF
410
or FIN. This is useful to reduce the number of packets sent.
412
.SS "stream.end(buffer)"
413
Same as above but with a \fBbuffer\fR.
415
.SS "stream.destroy()"
416
Closes the underlying file descriptor. Stream will not emit any more events.
449
or FIN\. This is useful to reduce the number of packets sent\.
451
.SS "stream\.end(buffer)"
452
Same as above but with a \fBbuffer\fR\|\.
454
.SS "stream\.destroy()"
455
Closes the underlying file descriptor\. Stream will not emit any more events\.
418
457
.SH "Global Objects"
419
These object are available in the global scope and can be accessed from anywhere.
458
These object are available in the global scope and can be accessed from anywhere\.
422
The global namespace object.
461
The global namespace object\.
425
The process object. Most stuff lives in here. See the \fB'process object'\fR
464
The process object\. See the \fB\'process object\'\fR section\.
429
To require modules. See the \fB'Modules'\fR section.
467
To require modules\. See the \fB\'Modules\'\fR section\.
432
An array of search paths for \fBrequire()\fR. This array can be modified to add custom paths.
470
An array of search paths for \fBrequire()\fR\|\. This array can be modified to add custom paths\.
435
473
Example: add a new path to the beginning of the search list
1082
var sys = require('sys'),
1083
spawn = require('child_process').spawn,
1084
child = spawn('bad_command');
1085
child.stderr.addListener('data', function (data) {
1086
if (/^execvp\\(\\)/.test(data.asciiSlice(0,data.length))) {
1087
sys.puts('Failed to start child process.');
1096
See also: \fBchild_process.exec()\fR
1098
.SS "child.kill(signal)"
1099
Send a signal to the child process. If no argument is given, the process will
1100
be sent \fB'SIGTERM'\fR. See \fBsignal(7)\fR for a list of available signals.
1105
var sys = require('sys'),
1106
spawn = require('child_process').spawn,
1107
grep = spawn('grep', ['ssh']);
1108
grep.addListener('exit', function (code, signal) {
1109
sys.puts('child process terminated due to receipt of signal '+signal);
1111
// send SIGHUP to process
1112
grep.kill('SIGHUP');
1119
Note that while the function is called \fBkill\fR, the signal delivered to the child
1120
process may not actually kill it. \fBkill\fR really just sends a signal to a process.
1126
The PID of the child process.
1134
var sys = require('sys'),
1135
spawn = require('child_process').spawn,
1136
grep = spawn('grep', ['ssh']);
1137
sys.puts('Spawned child pid: ' + grep.pid);
1144
.SS "child.stdin.write(data, encoding)"
1145
Write data to the child process's \fBstdin\fR. The second argument is optional and
1146
specifies the encoding: possible values are \fB'utf8'\fR, \fB'ascii'\fR, and \fB'binary'\fR.
1149
Example: A very elaborate way to run 'ps ax | grep ssh'
1154
var sys = require('sys'),
1155
spawn = require('child_process').spawn,
1156
ps = spawn('ps', ['ax']),
1157
grep = spawn('grep', ['ssh']);
1158
ps.stdout.addListener('data', function (data) {
1159
grep.stdin.write(data);
1161
ps.stderr.addListener('data', function (data) {
1162
sys.print('ps stderr: ' + data);
1164
ps.addListener('exit', function (code) {
1166
sys.puts('ps process exited with code ' + code);
1170
grep.stdout.addListener('data', function (data) {
1173
grep.stderr.addListener('data', function (data) {
1174
sys.print('grep stderr: ' + data);
1176
grep.addListener('exit', function (code) {
1178
sys.puts('grep process exited with code ' + code);
1186
.SS "child.stdin.end()"
1187
Closes the child process's \fBstdin\fR stream. This often causes the child process to terminate.
1195
var sys = require('sys'),
1196
spawn = require('child_process').spawn,
1197
grep = spawn('grep', ['ssh']);
1198
grep.addListener('exit', function (code) {
1199
sys.puts('child process exited with code ' + code);
1207
.SS "child_process.exec(command, [options, ] callback)"
1242
var spawn = require(\'child_process\')\.spawn,
1243
child = spawn(\'bad_command\');
1244
child\.stderr\.on(\'data\', function (data) {
1245
if (/^execvp\\(\\)/\.test(data\.asciiSlice(0,data\.length))) {
1246
console\.log(\'Failed to start child process\.\');
1255
See also: \fBchild_process\.exec()\fR
1257
.SS "child_process\.exec(command, [options], callback)"
1208
1258
High\-level way to execute a command as a child process, buffer the
1209
output, and return it all in a callback.
1259
output, and return it all in a callback\.
1214
var sys = require('sys'),
1215
exec = require('child_process').exec,
1264
var sys = require(\'sys\'),
1265
exec = require(\'child_process\')\.exec,
1217
child = exec('cat *.js bad_file | wc \-l',
1267
child = exec(\'cat *\.js bad_file | wc \-l\',
1218
1268
function (error, stdout, stderr) {
1219
sys.print('stdout: ' + stdout);
1220
sys.print('stderr: ' + stderr);
1269
sys\.print(\'stdout: \' + stdout);
1270
sys\.print(\'stderr: \' + stderr);
1221
1271
if (error !== null) {
1222
sys.puts('exec error: ' + error);
1272
console\.log(\'exec error: \' + error);
1231
The callback gets the arguments \fB(error, stdout, stderr)\fR. On success, \fBerror\fR
1232
will be \fBnull\fR. On error, \fBerror\fR will be an instance of \fBError\fR and \fBerr.code\fR
1233
will be the exit code of the child process, and \fBerr.signal\fR will be set to the
1234
signal that terminated the process.
1281
The callback gets the arguments \fB(error, stdout, stderr)\fR\|\. On success, \fBerror\fR
1282
will be \fBnull\fR\|\. On error, \fBerror\fR will be an instance of \fBError\fR and \fBerr\.code\fR
1283
will be the exit code of the child process, and \fBerr\.signal\fR will be set to the
1284
signal that terminated the process\.
1237
There is a second optional argument to specify several options. The default options are
1287
There is a second optional argument to specify several options\. The default options are
1292
{ encoding: \'utf8\'
1244
1294
, maxBuffer: 200*1024
1245
, killSignal: 'SIGKILL'
1295
, killSignal: \'SIGKILL\'
1302
\fBScript.runInThisContext\fR does not have access to the local scope, so \fBlocalVar\fR is unchanged. \fBeval\fR does have access to the local scope, so \fBlocalVar\fR is changed.
1305
In case of syntax error in \fBcode\fR, \fBScript.runInThisContext\fR emits the syntax error to stderr
1306
and throws.an exception.
1308
.SS "Script.runInNewContext(code, sandbox, filename)"
1309
\fBScript.runInNewContext\fR compiles \fBcode\fR to run in \fBsandbox\fR as if it were loaded from \fBfilename\fR,
1310
then runs it and returns the result. Running code does not have access to local scope and
1311
the object \fBsandbox\fR will be used as the global object for \fBcode\fR. \fBsandbox\fR and \fBfilename\fR are optional.
1314
Example: compile and execute code that increments a global variable and sets a new one.
1315
These globals are contained in the sandbox.
1379
\fBScript\.runInThisContext\fR does not have access to the local scope, so \fBlocalVar\fR is unchanged\. \fBeval\fR does have access to the local scope, so \fBlocalVar\fR is changed\.
1382
In case of syntax error in \fBcode\fR, \fBScript\.runInThisContext\fR emits the syntax error to stderr
1383
and throws\.an exception\.
1385
.SS "Script\.runInNewContext(code, [sandbox], [filename])"
1386
\fBScript\.runInNewContext\fR compiles \fBcode\fR to run in \fBsandbox\fR as if it were loaded from \fBfilename\fR,
1387
then runs it and returns the result\. Running code does not have access to local scope and
1388
the object \fBsandbox\fR will be used as the global object for \fBcode\fR\|\. \fBsandbox\fR and \fBfilename\fR are optional\.
1391
Example: compile and execute code that increments a global variable and sets a new one\.
1392
These globals are contained in the sandbox\.
1320
var sys = require('sys'),
1321
Script = process.binding('evals').Script,
1397
var sys = require(\'sys\'),
1398
Script = process\.binding(\'evals\')\.Script,
1326
Script.runInNewContext(
1327
'count += 1; name = "kitty"', sandbox, 'myfile.js');
1328
sys.puts(sys.inspect(sandbox));
1329
// { animal: 'cat', count: 3, name: 'kitty' }
1403
Script\.runInNewContext(
1404
\'count += 1; name = "kitty"\', sandbox, \'myfile\.js\');
1405
console\.log(sys\.inspect(sandbox));
1406
// { animal: \'cat\', count: 3, name: \'kitty\' }
1336
Note that running untrusted code is a tricky business requiring great care. To prevent accidental
1337
global variable leakage, \fBScript.runInNewContext\fR is quite useful, but safely running untrusted code
1338
requires a separate process.
1413
Note that running untrusted code is a tricky business requiring great care\. To prevent accidental
1414
global variable leakage, \fBScript\.runInNewContext\fR is quite useful, but safely running untrusted code
1415
requires a separate process\.
1341
In case of syntax error in \fBcode\fR, \fBScript.runInThisContext\fR emits the syntax error to stderr
1342
and throws an exception.
1418
In case of syntax error in \fBcode\fR, \fBScript\.runInThisContext\fR emits the syntax error to stderr
1419
and throws an exception\.
1344
.SS "new Script(code, filename)"
1421
.SS "new Script(code, [filename])"
1345
1422
\fBnew Script\fR compiles \fBcode\fR as if it were loaded from \fBfilename\fR,
1346
but does not run it. Instead, it returns a \fBScript\fR object representing this compiled code.
1347
This script can be run later many times using methods below.
1348
The returned script is not bound to any global object.
1349
It is bound before each run, just for that run. \fBfilename\fR is optional.
1423
but does not run it\. Instead, it returns a \fBScript\fR object representing this compiled code\.
1424
This script can be run later many times using methods below\.
1425
The returned script is not bound to any global object\.
1426
It is bound before each run, just for that run\. \fBfilename\fR is optional\.
1352
1429
In case of syntax error in \fBcode\fR, \fBnew Script\fR emits the syntax error to stderr
1353
and throws an exception.
1430
and throws an exception\.
1355
.SS "script.runInThisContext()"
1356
Similar to \fBScript.runInThisContext\fR (note capital 'S'), but now being a method of a precompiled Script object. \fBscript.runInThisContext\fR runs the code of \fBscript\fR and returns the result.
1432
.SS "script\.runInThisContext()"
1433
Similar to \fBScript\.runInThisContext\fR (note capital \'S\'), but now being a method of a precompiled Script object\. \fBscript\.runInThisContext\fR runs the code of \fBscript\fR and returns the result\.
1357
1434
Running code does not have access to local scope, but does have access to the \fBglobal\fR object
1358
(v8: in actual context).
1435
(v8: in actual context)\.
1361
Example of using \fBscript.runInThisContext\fR to compile code once and run it multiple times:
1438
Example of using \fBscript\.runInThisContext\fR to compile code once and run it multiple times:
1366
var sys = require('sys'),
1367
Script = process.binding('evals').Script,
1443
var Script = process\.binding(\'evals\')\.Script,
1370
scriptObj = new Script('globalVar += 1', 'myfile.js');
1446
scriptObj = new Script(\'globalVar += 1\', \'myfile\.js\');
1371
1447
for (i = 0; i < 1000 ; i += 1) {
1372
scriptObj.runInThisContext();
1448
scriptObj\.runInThisContext();
1374
sys.puts(globalVar);
1450
console\.log(globalVar);
1381
.SS "script.runInNewContext(sandbox)"
1382
Similar to \fBScript.runInNewContext\fR (note capital 'S'), but now being a method of a precompiled Script object. \fBscript.runInNewContext\fR runs the code of \fBscript\fR with \fBsandbox\fR as the global object and returns the result.
1383
Running code does not have access to local scope. \fBsandbox\fR is optional.
1457
.SS "script\.runInNewContext([sandbox])"
1458
Similar to \fBScript\.runInNewContext\fR (note capital \'S\'), but now being a method of a precompiled Script object\. \fBscript\.runInNewContext\fR runs the code of \fBscript\fR with \fBsandbox\fR as the global object and returns the result\.
1459
Running code does not have access to local scope\. \fBsandbox\fR is optional\.
1386
Example: compile code that increments a global variable and sets one, then execute this code multiple times.
1387
These globals are contained in the sandbox.
1462
Example: compile code that increments a global variable and sets one, then execute this code multiple times\.
1463
These globals are contained in the sandbox\.
1392
var sys = require('sys'),
1393
Script = process.binding('evals').Script,
1468
var sys = require(\'sys\'),
1469
Script = process\.binding(\'evals\')\.Script,
1399
1475
scriptObj = new Script(
1400
'count += 1; name = "kitty"', 'myfile.js');
1476
\'count += 1; name = "kitty"\', \'myfile\.js\');
1401
1477
for (i = 0; i < 10 ; i += 1) {
1402
scriptObj.runInNewContext(sandbox);
1478
scriptObj\.runInNewContext(sandbox);
1404
sys.puts(sys.inspect(sandbox));
1405
// { animal: 'cat', count: 12, name: 'kitty' }
1480
console\.log(sys\.inspect(sandbox));
1481
// { animal: \'cat\', count: 12, name: \'kitty\' }
1412
Note that running untrusted code is a tricky business requiring great care. To prevent accidental
1413
global variable leakage, \fBscript.runInNewContext\fR is quite useful, but safely running untrusted code
1414
requires a separate process.
1488
Note that running untrusted code is a tricky business requiring great care\. To prevent accidental
1489
global variable leakage, \fBscript\.runInNewContext\fR is quite useful, but safely running untrusted code
1490
requires a separate process\.
1416
1492
.SH "File System"
1417
File I/O is provided by simple wrappers around standard POSIX functions. To
1418
use this module do \fBrequire('fs')\fR. All the methods have asynchronous and
1493
File I/O is provided by simple wrappers around standard POSIX functions\. To
1494
use this module do \fBrequire(\'fs\')\fR\|\. All the methods have asynchronous and
1422
The asynchronous form always take a completion callback as its last argument.
1498
The asynchronous form always take a completion callback as its last argument\.
1423
1499
The arguments passed to the completion callback depend on the method, but the
1424
first argument is always reserved for an exception. If the operation was
1425
completed successfully, then the first argument will be \fBnull\fR or \fBundefined\fR.
1500
first argument is always reserved for an exception\. If the operation was
1501
completed successfully, then the first argument will be \fBnull\fR or \fBundefined\fR\|\.
1428
1504
Here is an example of the asynchronous version:
1547
See the \fBfs.Stats\fR section below for more information.
1549
.SS "fs.statSync(path), fs.lstatSync(path), fs.fstatSync(fd)"
1550
Synchronous stat(2), lstat(2) or fstat(2). Returns an instance of \fBfs.Stats\fR.
1552
.SS "fs.link(srcpath, dstpath, callback)"
1553
Asynchronous link(2). No arguments other than a possible exception are given to the completion callback.
1555
.SS "fs.linkSync(dstpath, srcpath)"
1556
Synchronous link(2).
1558
.SS "fs.symlink(linkdata, path, callback)"
1559
Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback.
1561
.SS "fs.symlinkSync(linkdata, path)"
1562
Synchronous symlink(2).
1564
.SS "fs.readlink(path, callback)"
1565
Asynchronous readlink(2). The callback gets two arguments \fB(err, resolvedPath)\fR.
1567
.SS "fs.readlinkSync(path)"
1568
Synchronous readlink(2). Returns the resolved path.
1570
.SS "fs.realpath(path, callback)"
1571
Asynchronous realpath(2). The callback gets two arguments \fB(err, resolvedPath)\fR.
1573
.SS "fs.realpathSync(path)"
1574
Synchronous realpath(2). Returns the resolved path.
1576
.SS "fs.unlink(path, callback)"
1577
Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback.
1579
.SS "fs.unlinkSync(path)"
1580
Synchronous unlink(2).
1582
.SS "fs.rmdir(path, callback)"
1583
Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.
1585
.SS "fs.rmdirSync(path)"
1586
Synchronous rmdir(2).
1588
.SS "fs.mkdir(path, mode, callback)"
1589
Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback.
1591
.SS "fs.mkdirSync(path, mode)"
1592
Synchronous mkdir(2).
1594
.SS "fs.readdir(path, callback)"
1595
Asynchronous readdir(3). Reads the contents of a directory.
1621
See the \fBfs\.Stats\fR section below for more information\.
1623
.SS "fs\.lstat(path, [callback])"
1624
Asynchronous lstat(2)\. The callback gets two arguments \fB(err, stats)\fR where \fBstats\fR is a \fBfs\.Stats\fR object\.
1626
.SS "fs\.fstat(fd, [callback])"
1627
Asynchronous fstat(2)\. The callback gets two arguments \fB(err, stats)\fR where \fBstats\fR is a \fBfs\.Stats\fR object\.
1629
.SS "fs\.statSync(path)"
1630
Synchronous stat(2)\. Returns an instance of \fBfs\.Stats\fR\|\.
1632
.SS "fs\.lstatSync(path)"
1633
Synchronous lstat(2)\. Returns an instance of \fBfs\.Stats\fR\|\.
1635
.SS "fs\.fstatSync(fd)"
1636
Synchronous fstat(2)\. Returns an instance of \fBfs\.Stats\fR\|\.
1638
.SS "fs\.link(srcpath, dstpath, [callback])"
1639
Asynchronous link(2)\. No arguments other than a possible exception are given to the completion callback\.
1641
.SS "fs\.linkSync(dstpath, srcpath)"
1642
Synchronous link(2)\.
1644
.SS "fs\.symlink(linkdata, path, [callback])"
1645
Asynchronous symlink(2)\. No arguments other than a possible exception are given to the completion callback\.
1647
.SS "fs\.symlinkSync(linkdata, path)"
1648
Synchronous symlink(2)\.
1650
.SS "fs\.readlink(path, [callback])"
1651
Asynchronous readlink(2)\. The callback gets two arguments \fB(err, resolvedPath)\fR\|\.
1653
.SS "fs\.readlinkSync(path)"
1654
Synchronous readlink(2)\. Returns the resolved path\.
1656
.SS "fs\.realpath(path, [callback])"
1657
Asynchronous realpath(2)\. The callback gets two arguments \fB(err, resolvedPath)\fR\|\.
1659
.SS "fs\.realpathSync(path)"
1660
Synchronous realpath(2)\. Returns the resolved path\.
1662
.SS "fs\.unlink(path, [callback])"
1663
Asynchronous unlink(2)\. No arguments other than a possible exception are given to the completion callback\.
1665
.SS "fs\.unlinkSync(path)"
1666
Synchronous unlink(2)\.
1668
.SS "fs\.rmdir(path, [callback])"
1669
Asynchronous rmdir(2)\. No arguments other than a possible exception are given to the completion callback\.
1671
.SS "fs\.rmdirSync(path)"
1672
Synchronous rmdir(2)\.
1674
.SS "fs\.mkdir(path, mode, [callback])"
1675
Asynchronous mkdir(2)\. No arguments other than a possible exception are given to the completion callback\.
1677
.SS "fs\.mkdirSync(path, mode)"
1678
Synchronous mkdir(2)\.
1680
.SS "fs\.readdir(path, [callback])"
1681
Asynchronous readdir(3)\. Reads the contents of a directory\.
1596
1682
The callback gets two arguments \fB(err, files)\fR where \fBfiles\fR is an array of
1597
the names of the files in the directory excluding \fB'.'\fR and \fB'..'\fR.
1599
.SS "fs.readdirSync(path)"
1600
Synchronous readdir(3). Returns an array of filenames excluding \fB'.'\fR and \fB'..'\fR.
1602
.SS "fs.close(fd, callback)"
1603
Asynchronous close(2). No arguments other than a possible exception are given to the completion callback.
1605
.SS "fs.closeSync(fd)"
1606
Synchronous close(2).
1608
.SS "fs.open(path, flags, mode, callback)"
1609
Asynchronous file open. See open(2). Flags can be 'r', 'r+', 'w', 'w+', 'a',
1610
or 'a+'. The callback gets two arguments \fB(err, fd)\fR.
1612
.SS "fs.openSync(path, flags, mode)"
1613
Synchronous open(2).
1615
.SS "fs.write(fd, buffer, offset, length, position, callback)"
1616
Write \fBbuffer\fR to the file specified by \fBfd\fR.
1619
\fBoffset\fR and \fBlength\fR determine the part of the buffer to be written.
1622
\fBposition\fR refers to the offset from the beginning of the file where this data
1623
should be written. If \fBposition\fR is \fBnull\fR, the data will be written at the
1628
The callback will be given two arguments \fB(err, written)\fR where \fBwritten\fR
1629
specifies how many \fIbytes\fR were written.
1631
.SS "fs.writeSync(fd, data, position, encoding)"
1632
Synchronous version of \fBfs.write()\fR. Returns the number of bytes written.
1634
.SS "fs.read(fd, buffer, offset, length, position, callback)"
1635
Read data from the file specified by \fBfd\fR.
1638
\fBbuffer\fR is the buffer that the data will be written to.
1641
\fBoffset\fR is offset within the buffer where writing will start.
1644
\fBlength\fR is an integer specifying the number of bytes to read.
1647
\fBposition\fR is an integer specifying where to begin reading from in the file.
1648
If \fBposition\fR is \fBnull\fR, data will be read from the current file position.
1651
The callback is given the two arguments, \fB(err, bytesRead)\fR.
1653
.SS "fs.readSync(fd, buffer, offset, length, position)"
1654
Synchronous version of \fBfs.read\fR. Returns the number of \fBbytesRead\fR.
1656
.SS "fs.readFile(filename, [encoding,] callback)"
1657
Asynchronously reads the entire contents of a file. Example:
1683
the names of the files in the directory excluding \fB\'\.\'\fR and \fB\'\.\.\'\fR\|\.
1685
.SS "fs\.readdirSync(path)"
1686
Synchronous readdir(3)\. Returns an array of filenames excluding \fB\'\.\'\fR and \fB\'\.\.\'\fR\|\.
1688
.SS "fs\.close(fd, [callback])"
1689
Asynchronous close(2)\. No arguments other than a possible exception are given to the completion callback\.
1691
.SS "fs\.closeSync(fd)"
1692
Synchronous close(2)\.
1694
.SS "fs\.open(path, flags, mode=0666, [callback])"
1695
Asynchronous file open\. See open(2)\. Flags can be \'r\', \'r+\', \'w\', \'w+\', \'a\',
1696
or \'a+\'\. The callback gets two arguments \fB(err, fd)\fR\|\.
1698
.SS "fs\.openSync(path, flags, mode=0666)"
1699
Synchronous open(2)\.
1701
.SS "fs\.write(fd, buffer, offset, length, position, [callback])"
1702
Write \fBbuffer\fR to the file specified by \fBfd\fR\|\.
1705
\fBoffset\fR and \fBlength\fR determine the part of the buffer to be written\.
1708
\fBposition\fR refers to the offset from the beginning of the file where this data
1709
should be written\. If \fBposition\fR is \fBnull\fR, the data will be written at the
1714
The callback will be given two arguments \fB(err, written)\fR where \fBwritten\fR
1715
specifies how many \fIbytes\fR were written\.
1717
.SS "fs\.write(fd, str, position, encoding=\'utf8\', [callback])"
1718
Write the entire string \fBstr\fR using the given \fBencoding\fR to the file specified
1722
\fBposition\fR refers to the offset from the beginning of the file where this data
1723
should be written\. If \fBposition\fR is \fBnull\fR, the data will be written at the
1728
The callback will be given two arguments \fB(err, written)\fR where \fBwritten\fR
1729
specifies how many \fIbytes\fR were written\.
1731
.SS "fs\.writeSync(fd, buffer, offset, length, position)"
1732
Synchronous version of buffer\-based \fBfs\.write()\fR\|\. Returns the number of bytes written\.
1734
.SS "fs\.writeSync(fd, str, position, encoding=\'utf8\')"
1735
Synchronous version of string\-based \fBfs\.write()\fR\|\. Returns the number of bytes written\.
1737
.SS "fs\.read(fd, buffer, offset, length, position, [callback])"
1738
Read data from the file specified by \fBfd\fR\|\.
1741
\fBbuffer\fR is the buffer that the data will be written to\.
1744
\fBoffset\fR is offset within the buffer where writing will start\.
1747
\fBlength\fR is an integer specifying the number of bytes to read\.
1750
\fBposition\fR is an integer specifying where to begin reading from in the file\.
1751
If \fBposition\fR is \fBnull\fR, data will be read from the current file position\.
1754
The callback is given the two arguments, \fB(err, bytesRead)\fR\|\.
1756
.SS "fs\.read(fd, length, position, encoding, [callback])"
1757
Read data from the file specified by \fBfd\fR\|\.
1760
\fBlength\fR is an integer specifying the number of bytes to read\.
1763
\fBposition\fR is an integer specifying where to begin reading from in the file\.
1764
If \fBposition\fR is \fBnull\fR, data will be read from the current file position\.
1767
\fBencoding\fR is the desired encoding of the string of data read in from \fBfd\fR\|\.
1770
The callback is given the three arguments, \fB(err, str, bytesRead)\fR\|\.
1772
.SS "fs\.readSync(fd, buffer, offset, length, position)"
1773
Synchronous version of buffer\-based \fBfs\.read\fR\|\. Returns the number of \fBbytesRead\fR\|\.
1775
.SS "fs\.readSync(fd, length, position, encoding)"
1776
Synchronous version of string\-based \fBfs\.read\fR\|\. Returns the number of \fBbytesRead\fR\|\.
1778
.SS "fs\.readFile(filename, [encoding], [callback])"
1779
Asynchronously reads the entire contents of a file\. Example:
1662
fs.readFile('/etc/passwd', function (err, data) {
1784
fs\.readFile(\'/etc/passwd\', function (err, data) {
1663
1785
if (err) throw err;
1860
Keys are lowercased. Values are not modified.
1863
In order to support the full spectrum of possible HTTP applications, Node's
1864
HTTP API is very low\-level. It deals with stream handling and message
1865
parsing only. It parses a message into headers and body but it does not
1866
parse the actual headers or the body.
1869
HTTPS is supported if OpenSSL is available on the underlying platform.
1872
This is an EventEmitter with the following events:
1874
.SS "Event: 'request'"
1972
Keys are lowercased\. Values are not modified\.
1975
In order to support the full spectrum of possible HTTP applications, Node\'s
1976
HTTP API is very low\-level\. It deals with stream handling and message
1977
parsing only\. It parses a message into headers and body but it does not
1978
parse the actual headers or the body\.
1981
HTTPS is supported if OpenSSL is available on the underlying platform\.
1984
This is an \fBEventEmitter\fR with the following events:
1986
.SS "Event: \'request\'"
1875
1987
\fBfunction (request, response) { }\fR
1878
\fBrequest\fR is an instance of \fBhttp.ServerRequest\fR and \fBresponse\fR is
1879
an instance of \fBhttp.ServerResponse\fR
1990
\fBrequest\fR is an instance of \fBhttp\.ServerRequest\fR and \fBresponse\fR is
1991
an instance of \fBhttp\.ServerResponse\fR
1881
.SS "Event: 'connection'"
1993
.SS "Event: \'connection\'"
1882
1994
\fBfunction (stream) { }\fR
1885
When a new TCP stream is established. \fBstream\fR is an object of type
1886
\fBnet.Stream\fR. Usually users will not want to access this event. The
1887
\fBstream\fR can also be accessed at \fBrequest.connection\fR.
1997
When a new TCP stream is established\. \fBstream\fR is an object of type
1998
\fBnet\.Stream\fR\|\. Usually users will not want to access this event\. The
1999
\fBstream\fR can also be accessed at \fBrequest\.connection\fR\|\.
1889
.SS "Event: 'close'"
2001
.SS "Event: \'close\'"
1890
2002
\fBfunction (errno) { }\fR
1893
Emitted when the server closes.
1895
.SS "http.createServer(requestListener, [options])"
1896
Returns a new web server object.
1899
The \fBoptions\fR argument is optional. The \fBoptions\fR argument accepts the same values as the
1900
options argument for \fBnet.Server\fR.
1903
The \fBrequestListener\fR is a function which is automatically
1904
added to the \fB'request'\fR event.
1906
.SS "Event: 'request'"
2005
Emitted when the server closes\.
2007
.SS "Event: \'request\'"
1907
2008
\fBfunction (request, response) {}\fR
1910
Emitted each time there is request. Note that there may be multiple requests
1911
per connection (in the case of keep\-alive connections).
2011
Emitted each time there is request\. Note that there may be multiple requests
2012
per connection (in the case of keep\-alive connections)\.
1913
.SS "Event: 'upgrade'"
2014
.SS "Event: \'upgrade\'"
1914
2015
\fBfunction (request, socket, head)\fR
1917
Emitted each time a client requests a http upgrade. If this event isn't
2018
Emitted each time a client requests a http upgrade\. If this event isn\'t
1918
2019
listened for, then clients requesting an upgrade will have their connections
1922
\fBrequest\fR is the arguments for the http request, as it is in the request event.
1925
\fBsocket\fR is the network socket between the server and client.
1928
\fBhead\fR is an instance of Buffer, the first packet of the upgraded stream, this may be empty.
2023
\fBrequest\fR is the arguments for the http request, as it is in the request event\.
2026
\fBsocket\fR is the network socket between the server and client\.
2029
\fBhead\fR is an instance of Buffer, the first packet of the upgraded stream, this may be empty\.
1933
After this event is emitted, the request's socket will not have a \fBdata\fR
2034
After this event is emitted, the request\'s socket will not have a \fBdata\fR
1934
2035
event listener, meaning you will need to bind to it in order to handle data
1935
sent to the server on that socket.
2036
sent to the server on that socket\.
1937
.SS "Event: 'clientError'"
2038
.SS "Event: \'clientError\'"
1938
2039
\fBfunction (exception) {}\fR
1941
If a client connection emits an 'error' event \- it will forwarded here.
1943
.SS "server.listen(port, hostname)"
1944
Begin accepting connections on the specified port and hostname. If the
2042
If a client connection emits an \'error\' event \- it will forwarded here\.
2044
.SS "http\.createServer(requestListener)"
2045
Returns a new web server object\.
2048
The \fBrequestListener\fR is a function which is automatically
2049
added to the \fB\'request\'\fR event\.
2051
.SS "server\.listen(port, [hostname], [callback])"
2052
Begin accepting connections on the specified port and hostname\. If the
1945
2053
hostname is omitted, the server will accept connections directed to any
1949
To listen to a unix socket, supply a filename instead of port and hostname.
1952
\fBIf you give a port number as a string, the system will interpret it as a filename in the current directory and create a unix socket.\fR
1955
This function is asynchronous. \fBlistening\fR will be emitted when the server
1956
is ready to accept connections.
1958
.SS "server.listen(path)"
1959
Start a UNIX socket server listening for connections on the given \fBpath\fR.
1960
This function is asynchronous. \fBlistening\fR will be emitted when the server
1961
is ready to accept connections.
1963
.SS "server.setSecure(credentials)"
1964
Enables HTTPS support for the server, with the crypto module credentials specifying the private key and certificate of the server, and optionally the CA certificates for use in client authentication.
1967
If the credentials hold one or more CA certificates, then the server will request for the client to submit a client certificate as part of the HTTPS connection handshake. The validity and content of this can be accessed via verifyPeer() and getPeerCertificate() from the server's request.connection.
1969
.SS "server.close()"
1970
Stops the server from accepting new connections.
1972
.SH "http.ServerRequest"
2054
IPv4 address (\fBINADDR_ANY\fR)\.
2057
To listen to a unix socket, supply a filename instead of port and hostname\.
2060
This function is asynchronous\. The last parameter \fBcallback\fR will be called
2061
when the server has been bound to the port\.
2063
.SS "server\.listen(path, [callback])"
2064
Start a UNIX socket server listening for connections on the given \fBpath\fR\|\.
2067
This function is asynchronous\. The last parameter \fBcallback\fR will be called
2068
when the server has been bound\.
2070
.SS "server\.setSecure(credentials)"
2071
Enables HTTPS support for the server, with the crypto module credentials specifying the private key and certificate of the server, and optionally the CA certificates for use in client authentication\.
2074
If the credentials hold one or more CA certificates, then the server will request for the client to submit a client certificate as part of the HTTPS connection handshake\. The validity and content of this can be accessed via verifyPeer() and getPeerCertificate() from the server\'s request\.connection\.
2076
.SS "server\.close()"
2077
Stops the server from accepting new connections\.
2079
.SH "http\.ServerRequest"
1973
2080
This object is created internally by a HTTP server\-\-not by
1974
the user\-\-and passed as the first argument to a \fB'request'\fR listener.
2081
the user\-\-and passed as the first argument to a \fB\'request\'\fR listener\.
1977
This is an EventEmitter with the following events:
2084
This is an \fBEventEmitter\fR with the following events:
2086
.SS "Event: \'data\'"
1980
2087
\fBfunction (chunk) { }\fR
1983
Emitted when a piece of the message body is received.
2090
Emitted when a piece of the message body is received\.
1986
2093
Example: A chunk of the body is given as the single
1987
argument. The transfer\-encoding has been decoded. The
1988
body chunk is a string. The body encoding is set with\fBrequest.setBodyEncoding()\fR.
2094
argument\. The transfer\-encoding has been decoded\. The
2095
body chunk is a string\. The body encoding is set with \fBrequest\.setBodyEncoding()\fR\|\.
2097
.SS "Event: \'end\'"
1991
2098
\fBfunction () { }\fR
1994
Emitted exactly once for each message. No arguments. After
1995
emitted no other events will be emitted on the request.
1997
.SS "request.method"
1998
The request method as a string. Read only. Example:\fB'GET'\fR, \fB'DELETE'\fR.
2001
Request URL string. This contains only the URL that is
2002
present in the actual HTTP request. If the request is:
2101
Emitted exactly once for each message\. No arguments\. After
2102
emitted no other events will be emitted on the request\.
2104
.SS "request\.method"
2105
The request method as a string\. Read only\. Example: \fB\'GET\'\fR, \fB\'DELETE\'\fR\|\.
2108
Request URL string\. This contains only the URL that is
2109
present in the actual HTTP request\. If the request is:
2007
GET /status?name=ryan HTTP/1.1\\r\\n
2114
GET /status?name=ryan HTTP/1\.1\\r\\n
2008
2115
Accept: text/plain\\r\\n
2114
2221
This method must only be called once on a message and it must
2115
be called before \fBresponse.end()\fR is called.
2222
be called before \fBresponse\.end()\fR is called\.
2117
.SS "response.write(chunk, encoding)"
2224
.SS "response\.write(chunk, encoding=\'ascii\')"
2118
2225
This method must be called after \fBwriteHead\fR was
2119
called. It sends a chunk of the response body. This method may
2120
be called multiple times to provide successive parts of the body.
2226
called\. It sends a chunk of the response body\. This method may
2227
be called multiple times to provide successive parts of the body\.
2123
If \fBchunk\fR is a string, the second parameter
2124
specifies how to encode it into a byte stream. By default the \fBencoding\fR is \fB'ascii'\fR.
2230
\fBchunk\fR can be a string or a buffer\. If \fBchunk\fR is a string,
2231
the second parameter specifies how to encode it into a byte stream\.
2232
By default the \fBencoding\fR is \fB\'ascii\'\fR\|\.
2127
2235
\fBNote\fR: This is the raw HTTP body and has nothing to do with
2128
higher\-level multi\-part body encodings that may be used.
2236
higher\-level multi\-part body encodings that may be used\.
2131
The first time \fBresponse.write()\fR is called, it will send the buffered
2132
header information and the first body to the client. The second time \fBresponse.write()\fR is called, Node assumes you're going to be streaming
2133
data, and sends that separately. That is, the response is buffered up to the
2134
first chunk of body.
2239
The first time \fBresponse\.write()\fR is called, it will send the buffered
2240
header information and the first body to the client\. The second time \fBresponse\.write()\fR is called, Node assumes you\'re going to be streaming
2241
data, and sends that separately\. That is, the response is buffered up to the
2242
first chunk of body\.
2136
.SS "response.end()"
2244
.SS "response\.end([data], [encoding])"
2137
2245
This method signals to the server that all of the response headers and body
2138
has been sent; that server should consider this message complete.
2139
The method, \fBresponse.end()\fR, MUST be called on each
2246
has been sent; that server should consider this message complete\.
2247
The method, \fBresponse\.end()\fR, MUST be called on each
2251
If \fBdata\fR is specified, it is equivalent to calling \fBresponse\.write(data, encoding)\fR
2252
followed by \fBresponse\.end()\fR\|\.
2143
2255
An HTTP client is constructed with a server address as its
2144
2256
argument, the returned handle is then used to issue one or more
2145
requests. Depending on the server connected to, the client might
2257
requests\. Depending on the server connected to, the client might
2146
2258
pipeline the requests or reestablish the stream after each
2147
stream. \fICurrently the implementation does not pipeline requests.\fR
2259
stream\. \fICurrently the implementation does not pipeline requests\.\fR
2150
Example of connecting to \fBgoogle.com\fR:
2262
Example of connecting to \fBgoogle\.com\fR:
2155
var sys = require('sys'),
2156
http = require('http');
2157
var google = http.createClient(80, 'www.google.com');
2158
var request = google.request('GET', '/',
2159
{'host': 'www.google.com'});
2160
request.addListener('response', function (response) {
2161
sys.puts('STATUS: ' + response.statusCode);
2162
sys.puts('HEADERS: ' + JSON.stringify(response.headers));
2163
response.setEncoding('utf8');
2164
response.addListener('data', function (chunk) {
2165
sys.puts('BODY: ' + chunk);
2267
var http = require(\'http\');
2268
var google = http\.createClient(80, \'www\.google\.com\');
2269
var request = google\.request(\'GET\', \'/\',
2270
{\'host\': \'www\.google\.com\'});
2272
request\.on(\'response\', function (response) {
2273
console\.log(\'STATUS: \' + response\.statusCode);
2274
console\.log(\'HEADERS: \' + JSON\.stringify(response\.headers));
2275
response\.setEncoding(\'utf8\');
2276
response\.on(\'data\', function (chunk) {
2277
console\.log(\'BODY: \' + chunk);
2174
.SS "http.createClient(port, host, secure, credentials)"
2175
Constructs a new HTTP client. \fBport\fR and \fBhost\fR refer to the server to be connected to. A
2176
stream is not established until a request is issued.
2179
\fBsecure\fR is an optional boolean flag to enable https support and \fBcredentials\fR is an optional credentials object from the crypto module, which may hold the client's private key, certificate, and a list of trusted CA certificates.
2182
If the connection is secure, but no explicit CA certificates are passed in the credentials, then node.js will default to the publicly trusted list of CA certificates, as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt
2184
.SS "client.request([method], path, [request_headers])"
2185
Issues a request; if necessary establishes stream. Returns a \fBhttp.ClientRequest\fR instance.
2188
\fBmethod\fR is optional and defaults to 'GET' if omitted.
2191
\fBrequest_headers\fR is optional.
2286
There are a few special headers that should be noted\.
2289
The \'Host\' header is not added by Node, and is usually required by
2293
Sending a \'Connection: keep\-alive\' will notify Node that the connection to
2294
the server should be persisted until the next request\.
2297
Sending a \'Content\-length\' header will disable the default chunked encoding\.
2301
.SS "Event: \'upgrade\'"
2302
\fBfunction (request, socket, head)\fR
2305
Emitted each time a server responds to a request with an upgrade\. If this event
2306
isn\'t being listened for, clients receiving an upgrade header will have their
2307
connections closed\.
2310
See the description of the \fBupgrade\fR event for \fBhttp\.Server\fR for further details\.
2312
.SS "http\.createClient(port, host=\'localhost\', secure=false, [credentials])"
2313
Constructs a new HTTP client\. \fBport\fR and \fBhost\fR refer to the server to be connected to\. A
2314
stream is not established until a request is issued\.
2317
\fBsecure\fR is an optional boolean flag to enable https support and \fBcredentials\fR is an optional credentials object from the crypto module, which may hold the client\'s private key, certificate, and a list of trusted CA certificates\.
2320
If the connection is secure, but no explicit CA certificates are passed in the credentials, then node\.js will default to the publicly trusted list of CA certificates, as given in http://mxr\.mozilla\.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata\.txt
2322
.SS "client\.request(method=\'GET\', path, [request_headers])"
2323
Issues a request; if necessary establishes stream\. Returns a \fBhttp\.ClientRequest\fR instance\.
2326
\fBmethod\fR is optional and defaults to \'GET\' if omitted\.
2329
\fBrequest_headers\fR is optional\.
2192
2330
Additional request headers might be added internally
2193
by Node. Returns a \fBClientRequest\fR object.
2331
by Node\. Returns a \fBClientRequest\fR object\.
2196
2334
Do remember to include the \fBContent\-Length\fR header if you
2197
plan on sending a body. If you plan on streaming the body, perhaps
2198
set \fBTransfer\-Encoding: chunked\fR.
2335
plan on sending a body\. If you plan on streaming the body, perhaps
2336
set \fBTransfer\-Encoding: chunked\fR\|\.
2201
\fINOTE\fR: the request is not complete. This method only sends the header of
2202
the request. One needs to call \fBrequest.end()\fR to finalize the request and
2203
retrieve the response. (This sounds convoluted but it provides a chance for
2204
the user to stream a body to the server with \fBrequest.write()\fR.)
2206
.SS "client.verifyPeer()"
2207
Returns true or false depending on the validity of the server's certificate in the context of the defined or default list of trusted CA certificates.
2209
.SS "client.getPeerCertificate()"
2210
Returns a JSON structure detailing the server's certificate, containing a dictionary with keys for the certificate 'subject', 'issuer', 'valid_from' and 'valid_to'
2212
.SH "http.ClientRequest"
2339
\fINOTE\fR: the request is not complete\. This method only sends the header of
2340
the request\. One needs to call \fBrequest\.end()\fR to finalize the request and
2341
retrieve the response\. (This sounds convoluted but it provides a chance for
2342
the user to stream a body to the server with \fBrequest\.write()\fR\|\.)
2344
.SS "client\.verifyPeer()"
2345
Returns true or false depending on the validity of the server\'s certificate in the context of the defined or default list of trusted CA certificates\.
2347
.SS "client\.getPeerCertificate()"
2348
Returns a JSON structure detailing the server\'s certificate, containing a dictionary with keys for the certificate \'subject\', \'issuer\', \'valid_from\' and \'valid_to\'
2350
.SH "http\.ClientRequest"
2213
2351
This object is created internally and returned from the \fBrequest()\fR method
2214
of a \fBhttp.Client\fR. It represents an \fIin\-progress\fR request whose header has
2218
To get the response, add a listener for \fB'response'\fR to the request object. \fB'response'\fR will be emitted from the request object when the response
2219
headers have been received. The \fB'response'\fR event is executed with one
2220
argument which is an instance of \fBhttp.ClientResponse\fR.
2223
During the \fB'response'\fR event, one can add listeners to the
2224
response object; particularly to listen for the \fB'data'\fR event. Note that
2225
the \fB'response'\fR event is called before any part of the response body is received,
2352
of a \fBhttp\.Client\fR\|\. It represents an \fIin\-progress\fR request whose header has
2356
To get the response, add a listener for \fB\'response\'\fR to the request object\. \fB\'response\'\fR will be emitted from the request object when the response
2357
headers have been received\. The \fB\'response\'\fR event is executed with one
2358
argument which is an instance of \fBhttp\.ClientResponse\fR\|\.
2361
During the \fB\'response\'\fR event, one can add listeners to the
2362
response object; particularly to listen for the \fB\'data\'\fR event\. Note that
2363
the \fB\'response\'\fR event is called before any part of the response body is received,
2226
2364
so there is no need to worry about racing to catch the first part of the
2227
body. As long as a listener for \fB'data'\fR is added during the \fB'response'\fR
2228
event, the entire body will be caught.
2365
body\. As long as a listener for \fB\'data\'\fR is added during the \fB\'response\'\fR
2366
event, the entire body will be caught\.
2234
request.addListener('response', function (response) {
2235
response.addListener('data', function (chunk) {
2236
sys.puts('BODY: ' + chunk);
2372
request\.on(\'response\', function (response) {
2373
response\.on(\'data\', function (chunk) {
2374
console\.log(\'BODY: \' + chunk);
2239
2377
// Bad \- misses all or part of the body
2240
request.addListener('response', function (response) {
2378
request\.on(\'response\', function (response) {
2241
2379
setTimeout(function () {
2242
response.addListener('data', function (chunk) {
2243
sys.puts('BODY: ' + chunk);
2380
response\.on(\'data\', function (chunk) {
2381
console\.log(\'BODY: \' + chunk);
2253
This is a writable stream.
2391
This is a \fBWritable Stream\fR\|\.
2256
2394
This is an \fBEventEmitter\fR with the following events:
2258
.SS "Event 'response'"
2396
.SS "Event \'response\'"
2259
2397
\fBfunction (response) { }\fR
2262
Emitted when a response is received to this request. This event is emitted only once. The\fBresponse\fR argument will be an instance of \fBhttp.ClientResponse\fR.
2400
Emitted when a response is received to this request\. This event is emitted only once\. The \fBresponse\fR argument will be an instance of \fBhttp\.ClientResponse\fR\|\.
2264
.SS "request.write(chunk, encoding='ascii')"
2265
Sends a chunk of the body. By calling this method
2402
.SS "request\.write(chunk, encoding=\'ascii\')"
2403
Sends a chunk of the body\. By calling this method
2266
2404
many times, the user can stream a request body to a
2267
server\-\-in that case it is suggested to use the\fB['Transfer\-Encoding', 'chunked']\fR header line when
2268
creating the request.
2405
server\-\-in that case it is suggested to use the \fB[\'Transfer\-Encoding\', \'chunked\']\fR header line when
2406
creating the request\.
2271
2409
The \fBchunk\fR argument should be an array of integers
2275
2413
The \fBencoding\fR argument is optional and only
2276
applies when \fBchunk\fR is a string. The encoding
2277
argument should be either \fB'utf8'\fR or \fB'ascii'\fR. By default the body uses ASCII encoding,
2281
Finishes sending the request. If any parts of the body are
2282
unsent, it will flush them to the stream. If the request is
2283
chunked, this will send the terminating \fB'0\\r\\n\\r\\n'\fR.
2285
.SH "http.ClientResponse"
2286
This object is created when making a request with \fBhttp.Client\fR. It is
2287
passed to the \fB'response'\fR event of the request object.
2290
The response implements the \fBreadable stream\fR interface.
2414
applies when \fBchunk\fR is a string\. The encoding
2415
argument should be either \fB\'utf8\'\fR or \fB\'ascii\'\fR\|\. By default the body uses ASCII encoding,
2418
.SS "request\.end([data], [encoding])"
2419
Finishes sending the request\. If any parts of the body are
2420
unsent, it will flush them to the stream\. If the request is
2421
chunked, this will send the terminating \fB\'0\\r\\n\\r\\n\'\fR\|\.
2424
If \fBdata\fR is specified, it is equivalent to calling \fBrequest\.write(data, encoding)\fR
2425
followed by \fBrequest\.end()\fR\|\.
2427
.SH "http\.ClientResponse"
2428
This object is created when making a request with \fBhttp\.Client\fR\|\. It is
2429
passed to the \fB\'response\'\fR event of the request object\.
2432
The response implements the \fBReadable Stream\fR interface\.
2434
.SS "Event: \'data\'"
2293
2435
\fBfunction (chunk) {}\fR
2296
Emitted when a piece of the message body is received.
2438
Emitted when a piece of the message body is received\.
2301
2443
Example: A chunk of the body is given as the single
2302
argument. The transfer\-encoding has been decoded. The
2303
body chunk a String. The body encoding is set with
2304
`response.setBodyEncoding()`.
2444
argument\. The transfer\-encoding has been decoded\. The
2445
body chunk a String\. The body encoding is set with
2446
`response\.setBodyEncoding()`\.
2452
.SS "Event: \'end\'"
2311
2453
\fBfunction () {}\fR
2314
Emitted exactly once for each message. No arguments. After
2315
emitted no other events will be emitted on the response.
2317
.SS "response.statusCode"
2318
The 3\-digit HTTP response status code. E.G. \fB404\fR.
2320
.SS "response.httpVersion"
2321
The HTTP version of the connected\-to server. Probably either\fB'1.1'\fR or \fB'1.0'\fR.
2322
Also \fBresponse.httpVersionMajor\fR is the first integer and \fBresponse.httpVersionMinor\fR is the second.
2324
.SS "response.headers"
2325
The response headers.
2327
.SS "response.setEncoding(encoding)"
2328
Set the encoding for the response body. Either \fB'utf8'\fR or \fB'binary'\fR.
2329
Defaults to \fB'binary'\fR.
2331
.SS "response.pause()"
2332
Pauses response from emitting events. Useful to throttle back a download.
2334
.SS "response.resume()"
2335
Resumes a paused response.
2337
.SS "response.client"
2338
A reference to the \fBhttp.Client\fR that this response belongs to.
2341
This class is used to create a TCP or UNIX server.
2456
Emitted exactly once for each message\. No arguments\. After
2457
emitted no other events will be emitted on the response\.
2459
.SS "response\.statusCode"
2460
The 3\-digit HTTP response status code\. E\.G\. \fB404\fR\|\.
2462
.SS "response\.httpVersion"
2463
The HTTP version of the connected\-to server\. Probably either \fB\'1\.1\'\fR or \fB\'1\.0\'\fR\|\.
2464
Also \fBresponse\.httpVersionMajor\fR is the first integer and \fBresponse\.httpVersionMinor\fR is the second\.
2466
.SS "response\.headers"
2467
The response headers object\.
2469
.SS "response\.setEncoding(encoding=null)"
2470
Set the encoding for the response body\. Either \fB\'utf8\'\fR, \fB\'ascii\'\fR, or \fB\'base64\'\fR\|\.
2471
Defaults to \fBnull\fR, which means that the \fB\'data\'\fR event will emit a \fBBuffer\fR object\.\.
2473
.SS "response\.pause()"
2474
Pauses response from emitting events\. Useful to throttle back a download\.
2476
.SS "response\.resume()"
2477
Resumes a paused response\.
2479
.SS "response\.client"
2480
A reference to the \fBhttp\.Client\fR that this response belongs to\.
2483
This class is used to create a TCP or UNIX server\.
2344
2486
Here is an example of a echo server which listens for connections
2350
var net = require('net');
2351
var server = net.createServer(function (stream) {
2352
stream.setEncoding('utf8');
2353
stream.addListener('connect', function () {
2354
stream.write('hello\\r\\n');
2356
stream.addListener('data', function (data) {
2359
stream.addListener('end', function () {
2360
stream.write('goodbye\\r\\n');
2492
var net = require(\'net\');
2493
var server = net\.createServer(function (stream) {
2494
stream\.setEncoding(\'utf8\');
2495
stream\.on(\'connect\', function () {
2496
stream\.write(\'hello\\r\\n\');
2498
stream\.on(\'data\', function (data) {
2499
stream\.write(data);
2501
stream\.on(\'end\', function () {
2502
stream\.write(\'goodbye\\r\\n\');
2364
server.listen(7000, 'localhost');
2506
server\.listen(8124, \'localhost\');
2371
To listen on the socket \fB'/tmp/echo.sock'\fR, the last line would just be
2513
To listen on the socket \fB\'/tmp/echo\.sock\'\fR, the last line would just be
2377
server.listen('/tmp/echo.sock');
2519
server\.listen(\'/tmp/echo\.sock\');
2384
This is an EventEmitter with the following events:
2386
.SS "Event: 'listening'"
2387
\fBfunction () {}\fR
2390
After \fBlisten()\fR is called, this event will notify that the server is ready
2391
to accept connections.
2393
.SS "Event: 'connection'"
2526
This is an \fBEventEmitter\fR with the following events:
2528
.SS "Event: \'connection\'"
2394
2529
\fBfunction (stream) {}\fR
2397
Emitted when a new connection is made. \fBstream\fR is an instance of \fBnet.Stream\fR.
2532
Emitted when a new connection is made\. \fBstream\fR is an instance of \fBnet\.Stream\fR\|\.
2399
.SS "Event: 'close'"
2534
.SS "Event: \'close\'"
2400
2535
\fBfunction () {}\fR
2403
Emitted when the server closes.
2405
.SS "net.createServer(connectionListener)"
2406
Creates a new TCP server. The \fBconnection_listener\fR argument is
2407
automatically set as a listener for the \fB'connection'\fR event.
2409
.SS "server.listen(port, host=null)"
2410
Tells the server to listen for TCP connections to \fBport\fR and \fBhost\fR.
2413
\fBhost\fR is optional. If \fBhost\fR is not specified the server will accept client
2414
connections on any network address.
2417
This function is asynchronous. The server will emit \fB'listening'\fR when it is
2418
safe to connect to it.
2420
.SS "server.close()"
2421
Stops the server from accepting new connections. This function is
2422
asynchronous, the server is finally closed when the server emits a \fB'close'\fR
2426
This object is an abstraction of of a TCP or UNIX socket. \fBnet.Stream\fR
2427
instance implement a duplex stream interface. They can be created by the
2538
Emitted when the server closes\.
2540
.SS "net\.createServer(connectionListener)"
2541
Creates a new TCP server\. The \fBconnectionListener\fR argument is
2542
automatically set as a listener for the \fB\'connection\'\fR event\.
2544
.SS "server\.listen(port, [host], [callback])"
2545
Begin accepting connections on the specified \fBport\fR and \fBhost\fR\|\. If the \fBhost\fR is omitted, the server will accept connections directed to any
2546
IPv4 address (\fBINADDR_ANY\fR)\.
2549
This function is asynchronous\. The last parameter \fBcallback\fR will be called
2550
when the server has been bound\.
2552
.SS "server\.listen(path, [callback])"
2553
Start a UNIX socket server listening for connections on the given \fBpath\fR\|\.
2556
This function is asynchronous\. The last parameter \fBcallback\fR will be called
2557
when the server has been bound\.
2559
.SS "server\.listenFD(fd)"
2560
Start a server listening for connections on the given file descriptor\.
2563
This file descriptor must have already had the \fBbind(2)\fR and \fBlisten(2)\fR system
2564
calls invoked on it\.
2566
.SS "server\.close()"
2567
Stops the server from accepting new connections\. This function is
2568
asynchronous, the server is finally closed when the server emits a \fB\'close\'\fR
2571
.SS "server\.maxConnections"
2572
Set this property to reject connections when the server\'s connection count gets high\.
2574
.SS "server\.connections"
2575
The number of concurrent connections on the server\.
2578
This object is an abstraction of of a TCP or UNIX socket\. \fBnet\.Stream\fR
2579
instance implement a duplex stream interface\. They can be created by the
2428
2580
user and used as a client (with \fBconnect()\fR) or they can be created by Node
2429
and passed to the user through the \fB'connection'\fR event of a server.
2432
\fBnet.Stream\fR instances are an EventEmitters with the following events:
2434
.SS "Event: 'connect'"
2435
\fBfunction () { }\fR
2438
Emitted when a stream connection successfully is established.
2439
See \fBconnect()\fR.
2441
.SS "Event: 'secure'"
2442
\fBfunction () { }\fR
2445
Emitted when a stream connection successfully establishes a HTTPS handshake with its peer.
2581
and passed to the user through the \fB\'connection\'\fR event of a server\.
2584
\fBnet\.Stream\fR instances are EventEmitters with the following events:
2586
.SS "Event: \'connect\'"
2587
\fBfunction () { }\fR
2590
Emitted when a stream connection successfully is established\.
2591
See \fBconnect()\fR\|\.
2593
.SS "Event: \'secure\'"
2594
\fBfunction () { }\fR
2597
Emitted when a stream connection successfully establishes a HTTPS handshake with its peer\.
2599
.SS "Event: \'data\'"
2448
2600
\fBfunction (data) { }\fR
2451
Emitted when data is received. The argument \fBdata\fR will be a \fBBuffer\fR or \fBString\fR. Encoding of data is set by \fBstream.setEncoding()\fR.
2452
(See the section on Readable Streams for more infromation.)
2455
\fBfunction () { }\fR
2458
Emitted when the other end of the stream sends a FIN packet. After this is
2459
emitted the \fBreadyState\fR will be \fB'writeOnly'\fR. One should probably just
2460
call \fBstream.end()\fR when this event is emitted.
2462
.SS "Event: 'timeout'"
2463
\fBfunction () { }\fR
2466
Emitted if the stream times out from inactivity. This is only to notify that
2467
the stream has been idle. The user must manually close the connection.
2470
See also: \fBstream.setTimeout()\fR
2472
.SS "Event: 'drain'"
2473
\fBfunction () { }\fR
2476
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
2478
.SS "Event: 'error'"
2603
Emitted when data is received\. The argument \fBdata\fR will be a \fBBuffer\fR or \fBString\fR\|\. Encoding of data is set by \fBstream\.setEncoding()\fR\|\.
2604
(See the section on \fBReadable Stream\fR for more information\.)
2606
.SS "Event: \'end\'"
2607
\fBfunction () { }\fR
2610
Emitted when the other end of the stream sends a FIN packet\. After this is
2611
emitted the \fBreadyState\fR will be \fB\'writeOnly\'\fR\|\. One should probably just
2612
call \fBstream\.end()\fR when this event is emitted\.
2614
.SS "Event: \'timeout\'"
2615
\fBfunction () { }\fR
2618
Emitted if the stream times out from inactivity\. This is only to notify that
2619
the stream has been idle\. The user must manually close the connection\.
2622
See also: \fBstream\.setTimeout()\fR
2624
.SS "Event: \'drain\'"
2625
\fBfunction () { }\fR
2628
Emitted when the write buffer becomes empty\. Can be used to throttle uploads\.
2630
.SS "Event: \'error\'"
2479
2631
\fBfunction (exception) { }\fR
2482
Emitted when an error occurs. The \fB'close'\fR event will be called directly
2483
following this event.
2634
Emitted when an error occurs\. The \fB\'close\'\fR event will be called directly
2635
following this event\.
2485
.SS "Event: 'close'"
2486
\fBfunction () { }\fR
2637
.SS "Event: \'close\'"
2638
\fBfunction (had_error) { }\fR
2489
Emitted once the stream is fully closed. The argument \fBhad_error\fR is a boolean which says if
2641
Emitted once the stream is fully closed\. The argument \fBhad_error\fR is a boolean which says if
2490
2642
the stream was closed due to a transmission
2493
.SS "net.createConnection(port, host='127.0.0.1')"
2645
.SS "net\.createConnection(port, host=\'127\.0\.0\.1\')"
2494
2646
Construct a new stream object and opens a stream to the specified \fBport\fR
2495
and \fBhost\fR. If the second parameter is omitted, localhost is assumed.
2647
and \fBhost\fR\|\. If the second parameter is omitted, localhost is assumed\.
2498
When the stream is established the \fB'connect'\fR event will be emitted.
2650
When the stream is established the \fB\'connect\'\fR event will be emitted\.
2500
.SS "stream.connect(port, host='127.0.0.1')"
2501
Opens a stream to the specified \fBport\fR and \fBhost\fR. \fBcreateConnection()\fR
2502
also opens a stream; normally this method is not needed. Use this only if
2652
.SS "stream\.connect(port, host=\'127\.0\.0\.1\')"
2653
Opens a stream to the specified \fBport\fR and \fBhost\fR\|\. \fBcreateConnection()\fR
2654
also opens a stream; normally this method is not needed\. Use this only if
2503
2655
a stream is closed and you want to reuse the object to connect to another
2507
This function is asynchronous. When the \fB'connect'\fR event is emitted the
2508
stream is established. If there is a problem connecting, the \fB'connect'\fR
2509
event will not be emitted, the \fB'error'\fR event will be emitted with
2512
.SS "stream.remoteAddress"
2513
The string representation of the remote IP address. For example,\fB'74.125.127.100'\fR or \fB'2001:4860:a005::68'\fR.
2516
This member is only present in server\-side connections.
2518
.SS "stream.readyState"
2519
Either \fB'closed'\fR, \fB'open'\fR, \fB'opening'\fR, \fB'readOnly'\fR, or \fB'writeOnly'\fR.
2521
.SS "stream.setEncoding(encoding)"
2522
Sets the encoding (either \fB'ascii'\fR, \fB'utf8'\fR, or \fB'binary'\fR) for data that is
2525
.SS "stream.setSecure(credentials)"
2526
Enables HTTPS support for the stream, with the crypto module credentials specifying the private key and certificate of the stream, and optionally the CA certificates for use in peer authentication.
2529
If the credentials hold one ore more CA certificates, then the stream will request for the peer to submit a client certificate as part of the HTTPS connection handshake. The validity and content of this can be accessed via verifyPeer() and getPeerCertificate().
2531
.SS "stream.verifyPeer()"
2532
Returns true or false depending on the validity of the peers's certificate in the context of the defined or default list of trusted CA certificates.
2534
.SS "stream.getPeerCertificate()"
2535
Returns a JSON structure detailing the peer's certificate, containing a dictionary with keys for the certificate 'subject', 'issuer', 'valid_from' and 'valid_to'
2537
.SS "stream.write(data, encoding='ascii')"
2538
Sends data on the stream. The second parameter specifies the encoding in
2659
This function is asynchronous\. When the \fB\'connect\'\fR event is emitted the
2660
stream is established\. If there is a problem connecting, the \fB\'connect\'\fR
2661
event will not be emitted, the \fB\'error\'\fR event will be emitted with
2664
.SS "stream\.remoteAddress"
2665
The string representation of the remote IP address\. For example, \fB\'74\.125\.127\.100\'\fR or \fB\'2001:4860:a005::68\'\fR\|\.
2668
This member is only present in server\-side connections\.
2670
.SS "stream\.readyState"
2671
Either \fB\'closed\'\fR, \fB\'open\'\fR, \fB\'opening\'\fR, \fB\'readOnly\'\fR, or \fB\'writeOnly\'\fR\|\.
2673
.SS "stream\.setEncoding(encoding=null)"
2674
Sets the encoding (either \fB\'ascii\'\fR, \fB\'utf8\'\fR, or \fB\'base64\'\fR) for data that is
2677
.SS "stream\.setSecure([credentials])"
2678
Enables HTTPS support for the stream, with the crypto module credentials specifying the private key and certificate of the stream, and optionally the CA certificates for use in peer authentication\.
2681
If the credentials hold one ore more CA certificates, then the stream will request for the peer to submit a client certificate as part of the HTTPS connection handshake\. The validity and content of this can be accessed via verifyPeer() and getPeerCertificate()\.
2683
.SS "stream\.verifyPeer()"
2684
Returns true or false depending on the validity of the peers\'s certificate in the context of the defined or default list of trusted CA certificates\.
2686
.SS "stream\.getPeerCertificate()"
2687
Returns a JSON structure detailing the peer\'s certificate, containing a dictionary with keys for the certificate \'subject\', \'issuer\', \'valid_from\' and \'valid_to\'
2689
.SS "stream\.write(data, encoding=\'ascii\')"
2690
Sends data on the stream\. The second parameter specifies the encoding in
2539
2691
the case of a string\-\-it defaults to ASCII because encoding to UTF8 is rather
2543
2695
Returns \fBtrue\fR if the entire data was flushed successfully to the kernel
2544
buffer. Returns \fBfalse\fR if all or part of the data was queued in user memory. \fB'drain'\fR will be emitted when the buffer is again free.
2547
Half\-closes the stream. I.E., it sends a FIN packet. It is possible the
2548
server will still send some data. After calling this \fBreadyState\fR will be \fB'readOnly'\fR.
2550
.SS "stream.destroy()"
2551
Ensures that no more I/O activity happens on this stream. Only necessary in
2552
case of errors (parse error or so).
2554
.SS "stream.pause()"
2555
Pauses the reading of data. That is, \fB'data'\fR events will not be emitted.
2556
Useful to throttle back an upload.
2558
.SS "stream.resume()"
2559
Resumes reading after a call to \fBpause()\fR.
2561
.SS "stream.setTimeout(timeout)"
2696
buffer\. Returns \fBfalse\fR if all or part of the data was queued in user memory\. \fB\'drain\'\fR will be emitted when the buffer is again free\.
2698
.SS "stream\.end([data], [encoding])"
2699
Half\-closes the stream\. I\.E\., it sends a FIN packet\. It is possible the
2700
server will still send some data\. After calling this \fBreadyState\fR will be \fB\'readOnly\'\fR\|\.
2703
If \fBdata\fR is specified, it is equivalent to calling \fBstream\.write(data, encoding)\fR
2704
followed by \fBstream\.end()\fR\|\.
2706
.SS "stream\.destroy()"
2707
Ensures that no more I/O activity happens on this stream\. Only necessary in
2708
case of errors (parse error or so)\.
2710
.SS "stream\.pause()"
2711
Pauses the reading of data\. That is, \fB\'data\'\fR events will not be emitted\.
2712
Useful to throttle back an upload\.
2714
.SS "stream\.resume()"
2715
Resumes reading after a call to \fBpause()\fR\|\.
2717
.SS "stream\.setTimeout(timeout)"
2562
2718
Sets the stream to timeout after \fBtimeout\fR milliseconds of inactivity on
2563
the stream. By default \fBnet.Stream\fR do not have a timeout.
2566
When an idle timeout is triggered the stream will receive a \fB'timeout'\fR
2567
event but the connection will not be severed. The user must manually \fBend()\fR
2568
or \fBdestroy()\fR the stream.
2571
If \fBtimeout\fR is 0, then the existing idle timeout is disabled.
2573
.SS "stream.setNoDelay(noDelay=true)"
2574
Disables the Nagle algorithm. By default TCP connections use the Nagle
2575
algorithm, they buffer data before sending it off. Setting \fBnoDelay\fR will
2576
immediately fire off data each time \fBstream.write()\fR is called.
2578
.SS "stream.setKeepAlive(enable=false, initialDelay)"
2719
the stream\. By default \fBnet\.Stream\fR do not have a timeout\.
2722
When an idle timeout is triggered the stream will receive a \fB\'timeout\'\fR
2723
event but the connection will not be severed\. The user must manually \fBend()\fR
2724
or \fBdestroy()\fR the stream\.
2727
If \fBtimeout\fR is 0, then the existing idle timeout is disabled\.
2729
.SS "stream\.setNoDelay(noDelay=true)"
2730
Disables the Nagle algorithm\. By default TCP connections use the Nagle
2731
algorithm, they buffer data before sending it off\. Setting \fBnoDelay\fR will
2732
immediately fire off data each time \fBstream\.write()\fR is called\.
2734
.SS "stream\.setKeepAlive(enable=false, [initialDelay])"
2579
2735
Enable/disable keep\-alive functionality, and optionally set the initial
2580
delay before the first keepalive probe is sent on an idle stream.
2736
delay before the first keepalive probe is sent on an idle stream\.
2581
2737
Set \fBinitialDelay\fR (in milliseconds) to set the delay between the last
2582
data packet received and the first keepalive probe. Setting 0 for
2738
data packet received and the first keepalive probe\. Setting 0 for
2583
2739
initialDelay will leave the value unchanged from the default
2584
(or previous) setting.
2740
(or previous) setting\.
2587
Use \fBrequire('crypto')\fR to access this module.
2590
The crypto module requires OpenSSL to be available on the underlying platform. It offers a way of encapsulating secure credentials to be used as part of a secure HTTPS net or http connection.
2593
It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.
2595
.SS "crypto.createCredentials(details)"
2743
Use \fBrequire(\'crypto\')\fR to access this module\.
2746
The crypto module requires OpenSSL to be available on the underlying platform\. It offers a way of encapsulating secure credentials to be used as part of a secure HTTPS net or http connection\.
2749
It also offers a set of wrappers for OpenSSL\'s hash, hmac, cipher, decipher, sign and verify methods\.
2751
.SS "crypto\.createCredentials(details)"
2596
2752
Creates a credentials object, with the optional details being a dictionary with keys:
2602
2758
\fBcert\fR : a string holding the PEM encoded certificate
2605
\fBca\fR : either a string or list of strings of PEM encoded CA certificates to trust.
2608
If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in
2609
http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt
2611
.SS "crypto.createHash(algorithm)"
2612
Creates and returns a hash object, a cryptographic hash with the given algorithm which can be used to generate hash digests.
2615
\fBalgorithm\fR is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are sha1, md5, sha256, sha512, etc. On recent releases, \fBopenssl list\-message\-digest\-algorithms\fR will display the available digest algorithms.
2617
.SS "hash.update(data)"
2618
Updates the hash content with the given \fBdata\fR. This can be called many times with new data as it is streamed.
2620
.SS "hash.digest(encoding)"
2621
Calculates the digest of all of the passed data to be hashed. The \fBencoding\fR can be 'hex', 'binary' or 'base64'.
2623
.SS "crypto.createHmac(algorithm, key)"
2624
Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.
2627
\fBalgorithm\fR is dependent on the available algorithms supported by OpenSSL \- see createHash above. \fBkey\fR is the hmac key to be used.
2629
.SS "hmac.update(data)"
2630
Update the hmac content with the given \fBdata\fR. This can be called many times with new data as it is streamed.
2632
.SS "hmac.digest(encoding)"
2633
Calculates the digest of all of the passed data to the hmac. The \fBencoding\fR can be 'hex', 'binary' or 'base64'.
2635
.SS "crypto.createCipher(algorithm, key)"
2636
Creates and returns a cipher object, with the given algorithm and key.
2639
\fBalgorithm\fR is dependent on OpenSSL, examples are aes192, etc. On recent releases, \fBopenssl list\-cipher\-algorithms\fR will display the available cipher algorithms.
2641
.SS "cipher.update(data, input_encoding, output_encoding)"
2642
Updates the cipher with \fBdata\fR, the encoding of which is given in \fBinput_encoding\fR and can be 'utf8', 'ascii' or 'binary'. The \fBoutput_encoding\fR specifies the output format of the enciphered data, and can be 'binary', 'base64' or 'hex'.
2645
Returns the enciphered contents, and can be called many times with new data as it is streamed.
2647
.SS "cipher.final(output_encoding)"
2648
Returns any remaining enciphered contents, with \fBoutput_encoding\fR as update above.
2650
.SS "crypto.createDecipher(algorithm, key)"
2651
Creates and returns a decipher object, with the given algorithm and key. This is the mirror of the cipher object above.
2653
.SS "decipher.update(data, input_encoding, output_encoding)"
2654
Updates the decipher with \fBdata\fR, which is encoded in 'binary', 'base64' or 'hex'. The \fBoutput_decoding\fR specifies in what format to return the deciphered plaintext \- either 'binary', 'ascii' or 'utf8'.
2656
.SS "decipher.final(output_encoding)"
2657
Returns any remaining plaintext which is deciphered, with `output_encoding' as update above.
2659
.SS "crypto.createSign(algorithm)"
2660
Creates and returns a signing object, with the given algorithm. On recent OpenSSL releases, \fBopenssl list\-public\-key\-algorithms\fR will display the available signing algorithms. Examples are 'RSA\-SHA256'.
2662
.SS "signer.update(data)"
2663
Updates the signer object with data. This can be called many times with new data as it is streamed.
2665
.SS "signer.sign(private_key, output_format)"
2666
Calculates the signature on all the updated data passed through the signer. \fBprivate_key\fR is a string containing the PEM encoded private key for signing.
2669
Returns the signature in \fBoutput_format\fR which can be 'binary', 'hex' or 'base64'
2671
.SS "crypto.createVerify(algorithm)"
2672
Creates and returns a verification object, with the given algorithm. This is the mirror of the signing object above.
2674
.SS "verifier.update(data)"
2675
Updates the verifyer object with data. This can be called many times with new data as it is streamed.
2677
.SS "verifier.verify(public_key, signature, signature_format)"
2678
Verifies the signed data by using the \fBpublic_key\fR which is a string containing the PEM encoded public key, and \fBsignature\fR, which is the previously calculates signature for the data, in the \fBsignature_format\fR which can be 'binary', 'hex' or 'base64'.
2681
Returns true or false depending on the validity of the signature for the data and public key.
2761
\fBca\fR : either a string or list of strings of PEM encoded CA certificates to trust\.
2764
If no \'ca\' details are given, then node\.js will use the default publicly trusted list of CAs as given in
2765
http://mxr\.mozilla\.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata\.txt
2767
.SS "crypto\.createHash(algorithm)"
2768
Creates and returns a hash object, a cryptographic hash with the given algorithm which can be used to generate hash digests\.
2771
\fBalgorithm\fR is dependent on the available algorithms supported by the version of OpenSSL on the platform\. Examples are sha1, md5, sha256, sha512, etc\. On recent releases, \fBopenssl list\-message\-digest\-algorithms\fR will display the available digest algorithms\.
2773
.SS "hash\.update(data)"
2774
Updates the hash content with the given \fBdata\fR\|\. This can be called many times with new data as it is streamed\.
2776
.SS "hash\.digest(encoding=\'binary\')"
2777
Calculates the digest of all of the passed data to be hashed\. The \fBencoding\fR can be \'hex\', \'binary\' or \'base64\'\.
2779
.SS "crypto\.createHmac(algorithm, key)"
2780
Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key\.
2783
\fBalgorithm\fR is dependent on the available algorithms supported by OpenSSL \- see createHash above\. \fBkey\fR is the hmac key to be used\.
2785
.SS "hmac\.update(data)"
2786
Update the hmac content with the given \fBdata\fR\|\. This can be called many times with new data as it is streamed\.
2788
.SS "hmac\.digest(encoding=\'binary\')"
2789
Calculates the digest of all of the passed data to the hmac\. The \fBencoding\fR can be \'hex\', \'binary\' or \'base64\'\.
2791
.SS "crypto\.createCipher(algorithm, key)"
2792
Creates and returns a cipher object, with the given algorithm and key\.
2795
\fBalgorithm\fR is dependent on OpenSSL, examples are aes192, etc\. On recent releases, \fBopenssl list\-cipher\-algorithms\fR will display the available cipher algorithms\.
2797
.SS "cipher\.update(data, input_encoding=\'binary\', output_encoding=\'binary\')"
2798
Updates the cipher with \fBdata\fR, the encoding of which is given in \fBinput_encoding\fR and can be \'utf8\', \'ascii\' or \'binary\'\. The \fBoutput_encoding\fR specifies the output format of the enciphered data, and can be \'binary\', \'base64\' or \'hex\'\.
2801
Returns the enciphered contents, and can be called many times with new data as it is streamed\.
2803
.SS "cipher\.final(output_encoding=\'binary\')"
2804
Returns any remaining enciphered contents, with \fBoutput_encoding\fR being one of: \'binary\', \'ascii\' or \'utf8\'\.
2806
.SS "crypto\.createDecipher(algorithm, key)"
2807
Creates and returns a decipher object, with the given algorithm and key\. This is the mirror of the cipher object above\.
2809
.SS "decipher\.update(data, input_encoding=\'binary\', output_encoding=\'binary\')"
2810
Updates the decipher with \fBdata\fR, which is encoded in \'binary\', \'base64\' or \'hex\'\. The \fBoutput_decoding\fR specifies in what format to return the deciphered plaintext \- either \'binary\', \'ascii\' or \'utf8\'\.
2812
.SS "decipher\.final(output_encoding=\'binary\')"
2813
Returns any remaining plaintext which is deciphered, with `output_encoding\' being one of: \'binary\', \'ascii\' or \'utf8\'\.
2815
.SS "crypto\.createSign(algorithm)"
2816
Creates and returns a signing object, with the given algorithm\. On recent OpenSSL releases, \fBopenssl list\-public\-key\-algorithms\fR will display the available signing algorithms\. Examples are \'RSA\-SHA256\'\.
2818
.SS "signer\.update(data)"
2819
Updates the signer object with data\. This can be called many times with new data as it is streamed\.
2821
.SS "signer\.sign(private_key, output_format=\'binary\')"
2822
Calculates the signature on all the updated data passed through the signer\. \fBprivate_key\fR is a string containing the PEM encoded private key for signing\.
2825
Returns the signature in \fBoutput_format\fR which can be \'binary\', \'hex\' or \'base64\'
2827
.SS "crypto\.createVerify(algorithm)"
2828
Creates and returns a verification object, with the given algorithm\. This is the mirror of the signing object above\.
2830
.SS "verifier\.update(data)"
2831
Updates the verifyer object with data\. This can be called many times with new data as it is streamed\.
2833
.SS "verifier\.verify(public_key, signature, signature_format=\'binary\')"
2834
Verifies the signed data by using the \fBpublic_key\fR which is a string containing the PEM encoded public key, and \fBsignature\fR, which is the previously calculates signature for the data, in the \fBsignature_format\fR which can be \'binary\', \'hex\' or \'base64\'\.
2837
Returns true or false depending on the validity of the signature for the data and public key\.
2684
Use \fBrequire('dns')\fR to access this module.
2840
Use \fBrequire(\'dns\')\fR to access this module\.
2687
Here is an example which resolves \fB'www.google.com'\fR then reverse
2688
resolves the IP addresses which are returned.
2843
Here is an example which resolves \fB\'www\.google\.com\'\fR then reverse
2844
resolves the IP addresses which are returned\.
2693
var dns = require('dns'),
2694
sys = require('sys');
2695
dns.resolve4('www.google.com', function (err, addresses) {
2849
var dns = require(\'dns\');
2850
dns\.resolve4(\'www\.google\.com\', function (err, addresses) {
2696
2851
if (err) throw err;
2697
sys.puts('addresses: ' + JSON.stringify(addresses));
2698
for (var i = 0; i < addresses.length; i++) {
2699
var a = addresses[i];
2700
dns.reverse(a, function (err, domains) {
2852
console\.log(\'addresses: \' + JSON\.stringify(addresses));
2853
addresses\.forEach(function (a) {
2854
dns\.reverse(a, function (err, domains) {
2702
sys.puts('reverse for ' + a + ' failed: ' +
2856
console\.log(\'reverse for \' + a + \' failed: \' +
2705
sys.puts('reverse for ' + a + ': ' +
2706
JSON.stringify(domains));
2859
console\.log(\'reverse for \' + a + \': \' +
2860
JSON\.stringify(domains));
2716
.SS "dns.resolve(domain, rrtype = 'A', callback)"
2717
Resolves a domain (e.g. \fB'google.com'\fR) into an array of the record types
2718
specified by rrtype. Valid rrtypes are \fBA\fR (IPV4 addresses), \fBAAAA\fR (IPV6
2870
.SS "dns\.lookup(domain, family=null, callback)"
2871
Resolves a domain (e\.g\. \fB\'google\.com\'\fR) into the first found A (IPv4) or
2872
AAAA (IPv6) record\.
2875
The callback has arguments \fB(err, address, family)\fR\|\. The \fBaddress\fR argument
2876
is a string representation of a IP v4 or v6 address\. The \fBfamily\fR argument
2877
is either the integer 4 or 6 and denotes the family of \fBaddress\fR (not
2878
neccessarily the value initially passed to \fBlookup\fR)\.
2880
.SS "dns\.resolve(domain, rrtype=\'A\', callback)"
2881
Resolves a domain (e\.g\. \fB\'google\.com\'\fR) into an array of the record types
2882
specified by rrtype\. Valid rrtypes are \fBA\fR (IPV4 addresses), \fBAAAA\fR (IPV6
2719
2883
addresses), \fBMX\fR (mail exchange records), \fBTXT\fR (text records), \fBSRV\fR (SRV
2720
records), and \fBPTR\fR (used for reverse IP lookups).
2884
records), and \fBPTR\fR (used for reverse IP lookups)\.
2723
The callback has arguments \fB(err, addresses)\fR. The type of each item
2887
The callback has arguments \fB(err, addresses)\fR\|\. The type of each item
2724
2888
in \fBaddresses\fR is determined by the record type, and described in the
2725
documentation for the corresponding lookup methods below.
2889
documentation for the corresponding lookup methods below\.
2728
On error, \fBerr\fR would be an instanceof \fBError\fR object, where \fBerr.errno\fR is
2729
one of the error codes listed below and \fBerr.message\fR is a string describing
2730
the error in English.
2892
On error, \fBerr\fR would be an instanceof \fBError\fR object, where \fBerr\.errno\fR is
2893
one of the error codes listed below and \fBerr\.message\fR is a string describing
2894
the error in English\.
2732
.SS "dns.resolve4(domain, callback)"
2733
The same as \fBdns.resolve()\fR, but only for IPv4 queries (\fBA\fR records). \fBaddresses\fR is an array of IPv4 addresses (e.g.
2896
.SS "dns\.resolve4(domain, callback)"
2897
The same as \fBdns\.resolve()\fR, but only for IPv4 queries (\fBA\fR records)\. \fBaddresses\fR is an array of IPv4 addresses (e\.g\.
2736
\fB['74.125.79.104', '74.125.79.105', '74.125.79.106']\fR).
2738
.SS "dns.resolve6(domain, callback)"
2739
The same as \fBdns.resolve4()\fR except for IPv6 queries (an \fBAAAA\fR query).
2741
.SS "dns.resolveMx(domain, callback)"
2742
The same as \fBdns.resolve()\fR, but only for mail exchange queries (\fBMX\fR records).
2900
\fB[\'74\.125\.79\.104\', \'74\.125\.79\.105\', \'74\.125\.79\.106\']\fR)\.
2902
.SS "dns\.resolve6(domain, callback)"
2903
The same as \fBdns\.resolve4()\fR except for IPv6 queries (an \fBAAAA\fR query)\.
2905
.SS "dns\.resolveMx(domain, callback)"
2906
The same as \fBdns\.resolve()\fR, but only for mail exchange queries (\fBMX\fR records)\.
2745
2909
\fBaddresses\fR is an array of MX records, each with a priority and an exchange
2746
attribute (e.g. \fB[{'priority': 10, 'exchange': 'mx.example.com'},...]\fR).
2748
.SS "dns.resolveTxt(domain, callback)"
2749
The same as \fBdns.resolve()\fR, but only for text queries (\fBTXT\fR records). \fBaddresses\fR is an array of the text records available for \fBdomain\fR (e.g., \fB['v=spf1 ip4:0.0.0.0 ~all']\fR).
2751
.SS "dns.resolveSrv(domain, callback)"
2752
The same as \fBdns.resolve()\fR, but only for service records (\fBSRV\fR records). \fBaddresses\fR is an array of the SRV records available for \fBdomain\fR. Properties
2753
of SRV records are priority, weight, port, and name (e.g., \fB[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]\fR).
2755
.SS "dns.reverse(ip, callback)"
2756
Reverse resolves an ip address to an array of domain names.
2910
attribute (e\.g\. \fB[{\'priority\': 10, \'exchange\': \'mx\.example\.com\'},\.\.\.]\fR)\.
2912
.SS "dns\.resolveTxt(domain, callback)"
2913
The same as \fBdns\.resolve()\fR, but only for text queries (\fBTXT\fR records)\. \fBaddresses\fR is an array of the text records available for \fBdomain\fR (e\.g\., \fB[\'v=spf1 ip4:0\.0\.0\.0 ~all\']\fR)\.
2915
.SS "dns\.resolveSrv(domain, callback)"
2916
The same as \fBdns\.resolve()\fR, but only for service records (\fBSRV\fR records)\. \fBaddresses\fR is an array of the SRV records available for \fBdomain\fR\|\. Properties
2917
of SRV records are priority, weight, port, and name (e\.g\., \fB[{\'priority\': 10, {\'weight\': 5, \'port\': 21223, \'name\': \'service\.example\.com\'}, \.\.\.]\fR)\.
2919
.SS "dns\.reverse(ip, callback)"
2920
Reverse resolves an ip address to an array of domain names\.
2759
The callback has arguments \fB(err, domains)\fR.
2923
The callback has arguments \fB(err, domains)\fR\|\.
2762
2926
If there an an error, \fBerr\fR will be non\-null and an instanceof the Error
2766
Each DNS query can return an error code.
2769
\fBdns.TEMPFAIL\fR: timeout, SERVFAIL or similar.
2772
\fBdns.PROTOCOL\fR: got garbled reply.
2775
\fBdns.NXDOMAIN\fR: domain does not exists.
2778
\fBdns.NODATA\fR: domain exists but no data of reqd type.
2781
\fBdns.NOMEM\fR: out of memory while processing.
2784
\fBdns.BADQUERY\fR: the query is malformed.
2930
Each DNS query can return an error code\.
2933
\fBdns\.TEMPFAIL\fR: timeout, SERVFAIL or similar\.
2936
\fBdns\.PROTOCOL\fR: got garbled reply\.
2939
\fBdns\.NXDOMAIN\fR: domain does not exists\.
2942
\fBdns\.NODATA\fR: domain exists but no data of reqd type\.
2945
\fBdns\.NOMEM\fR: out of memory while processing\.
2948
\fBdns\.BADQUERY\fR: the query is malformed\.
2953
Datagram sockets are available through \fBrequire(\'dgram\')\fR\|\. Datagrams are most commonly
2954
handled as IP/UDP messages, but they can also be used over Unix domain sockets\.
2956
.SS "Event: \'message\'"
2957
\fBfunction (msg, rinfo) { }\fR
2960
Emitted when a new datagram is available on a socket\. \fBmsg\fR is a \fBBuffer\fR and \fBrinfo\fR is
2961
an object with the sender\'s address information and the number of bytes in the datagram\.
2963
.SS "Event: \'listening\'"
2964
\fBfunction () { }\fR
2967
Emitted when a socket starts listening for datagrams\. This happens as soon as UDP sockets
2968
are created\. Unix domain sockets do not start listening until calling \fBbind()\fR on them\.
2970
.SS "Event: \'close\'"
2971
\fBfunction () { }\fR
2974
Emitted when a socket is closed with \fBclose()\fR\|\. No new \fBmessage\fR events will be emitted
2977
.SS "dgram\.createSocket(type, [callback])"
2978
Creates a datagram socket of the specified types\. Valid types are: \fBudp4\fR, \fBudp6\fR, and \fBunix_dgram\fR\|\.
2981
Takes an optional callback which is added as a listener for \fBmessage\fR events\.
2983
.SS "dgram\.send(buf, offset, length, path, [callback])"
2984
For Unix domain datagram sockets, the destination address is a pathname in the filesystem\.
2985
An optional callback may be supplied that is invoked after the \fBsendto\fR call is completed
2986
by the OS\. It is not safe to re\-use \fBbuf\fR until the callback is invoked\. Note that
2987
unless the socket is bound to a pathname with \fBbind()\fR there is no way to receive messages
2991
Example of sending a message to syslogd on OSX via Unix domain socket \fB/var/run/syslog\fR:
2996
var dgram = require(\'dgram\');
2997
var message = new Buffer("A message to log\.");
2998
var client = dgram\.createSocket("unix_dgram");
2999
client\.send(message, 0, message\.length, "/var/run/syslog",
3000
function (err, bytes) {
3004
console\.log("Wrote " + bytes + " bytes to socket\.");
3011
.SS "dgram\.send(buf, offset, length, port, address, [callback])"
3012
For UDP sockets, the destination port and IP address must be specified\. A string
3013
may be supplied for the \fBaddress\fR parameter, and it will be resolved with DNS\. An
3014
optional callback may be specified to detect any DNS errors and when \fBbuf\fR may be
3015
re\-used\. Note that DNS lookups will delay the time that a send takes place, at
3016
least until the next tick\. The only way to know for sure that a send has taken place
3017
is to use the callback\.
3020
Example of sending a UDP packet to a random port on \fBlocalhost\fR;
3025
var dgram = require(\'dgram\');
3026
var message = new Buffer("Some bytes");
3027
var client = dgram\.createSocket("udp4");
3028
client\.send(message, 0, message\.length, 41234, "localhost");
3035
.SS "dgram\.bind(path)"
3036
For Unix domain datagram sockets, start listening for incoming datagrams on a
3037
socket specified by \fBpath\fR\|\. Note that clients may \fBsend()\fR without \fBbind()\fR,
3038
but no datagrams will be received without a \fBbind()\fR\|\.
3041
Example of a Unix domain datagram server that echoes back all messages it receives:
3046
var dgram = require("dgram");
3047
var serverPath = "/tmp/dgram_server_sock";
3048
var server = dgram\.createSocket("unix_dgram");
3049
server\.on("message", function (msg, rinfo) {
3050
console\.log("got: " + msg + " from " + rinfo\.address);
3051
server\.send(msg, 0, msg\.length, rinfo\.address);
3053
server\.on("listening", function () {
3054
console\.log("server listening " + server\.address()\.address);
3056
server\.bind(serverPath);
3063
Example of a Unix domain datagram client that talks to this server:
3068
var dgram = require("dgram");
3069
var serverPath = "/tmp/dgram_server_sock";
3070
var clientPath = "/tmp/dgram_client_sock";
3071
var message = new Buffer("A message at " + (new Date()));
3072
var client = dgram\.createSocket("unix_dgram");
3073
client\.on("message", function (msg, rinfo) {
3074
console\.log("got: " + msg + " from " + rinfo\.address);
3076
client\.on("listening", function () {
3077
console\.log("client listening " + client\.address()\.address);
3078
client\.send(message, 0, message\.length, serverPath);
3080
client\.bind(clientPath);
3086
.SS "dgram\.bind(port, [address])"
3087
For UDP sockets, listen for datagrams on a named \fBport\fR and optional \fBaddress\fR\|\. If \fBaddress\fR is not specified, the OS will try to listen on all addresses\.
3090
Example of a UDP server listening on port 41234:
3095
var dgram = require("dgram");
3096
var server = dgram\.createSocket("udp4");
3097
var messageToSend = new Buffer("A message to send");
3098
server\.on("message", function (msg, rinfo) {
3099
console\.log("server got: " + msg + " from " +
3100
rinfo\.address + ":" + rinfo\.port);
3102
server\.on("listening", function () {
3103
var address = server\.address();
3104
console\.log("server listening " +
3105
address\.address + ":" + address\.port);
3107
server\.bind(41234);
3108
// server listening 0\.0\.0\.0:41234
3114
.SS "dgram\.close()"
3115
Close the underlying socket and stop listening for data on it\. UDP sockets
3116
automatically listen for messages, even if they did not call \fBbind()\fR\|\.
3118
.SS "dgram\.address()"
3119
Returns an object containing the address information for a socket\. For UDP sockets,
3120
this object will contain \fBaddress\fR and \fBport\fR\|\. For Unix domain sockets, it will contain
3121
only \fBaddress\fR\|\.
3123
.SS "dgram\.setBroadcast(flag)"
3124
Sets or clears the \fBSO_BROADCAST\fR socket option\. When this option is set, UDP packets
3125
may be sent to a local interface\'s broadcast address\.
3127
.SS "dgram\.setTTL(ttl)"
3128
Sets the \fBIP_TTL\fR socket option\. TTL stands for "Time to Live," but in this context it
3129
specifies the number of IP hops that a packet is allowed to go through\. Each router or
3130
gateway that forwards a packet decrements the TTL\. If the TTL is decremented to 0 by a
3131
router, it will not be forwarded\. Changing TTL values is typically done for network
3132
probes or when multicasting\.
3135
The argument to \fBsetTTL()\fR is a number of hops between 1 and 255\. The default on most
2789
3139
This module is used for writing unit tests for your applications, you can
2790
access it with \fBrequire('assert')\fR.
2792
.SS "assert.fail(actual, expected, message, operator)"
2793
Tests if \fBactual\fR is equal to \fBexpected\fR using the operator provided.
2795
.SS "assert.ok(value, message)"
2796
Tests if value is a \fBtrue\fR value, it is equivalent to \fBassert.equal(true, value, message);\fR
2798
.SS "assert.equal(actual, expected, message)"
2799
Tests shallow, coercive equality with the equal comparison operator ( \fB==\fR ).
2801
.SS "assert.notEqual(actual, expected, message)"
2802
Tests shallow, coercive non\-equality with the not equal comparison operator ( \fB!=\fR ).
2804
.SS "assert.deepEqual(actual, expected, message)"
2805
Tests for deep equality.
2807
.SS "assert.notDeepEqual(actual, expected, message)"
2808
Tests for any deep inequality.
2810
.SS "assert.strictEqual(actual, expected, message)"
2811
Tests strict equality, as determined by the strict equality operator ( \fB===\fR )
2813
.SS "assert.notStrictEqual(actual, expected, message)"
2814
Tests strict non\-equality, as determined by the strict not equal operator ( \fB!==\fR )
2816
.SS "assert.throws(block, error, message)"
2817
Expects \fBblock\fR to throw an error.
2819
.SS "assert.doesNotThrow(block, error, message)"
2820
Expects \fBblock\fR not to throw an error.
2822
.SS "assert.ifError(value)"
2823
Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, \fBerror\fR in callbacks.
3140
access it with \fBrequire(\'assert\')\fR\|\.
3142
.SS "assert\.fail(actual, expected, message, operator)"
3143
Tests if \fBactual\fR is equal to \fBexpected\fR using the operator provided\.
3145
.SS "assert\.ok(value, [message])"
3146
Tests if value is a \fBtrue\fR value, it is equivalent to \fBassert\.equal(true, value, message);\fR
3148
.SS "assert\.equal(actual, expected, [message])"
3149
Tests shallow, coercive equality with the equal comparison operator ( \fB==\fR )\.
3151
.SS "assert\.notEqual(actual, expected, [message])"
3152
Tests shallow, coercive non\-equality with the not equal comparison operator ( \fB!=\fR )\.
3154
.SS "assert\.deepEqual(actual, expected, [message])"
3155
Tests for deep equality\.
3157
.SS "assert\.notDeepEqual(actual, expected, [message])"
3158
Tests for any deep inequality\.
3160
.SS "assert\.strictEqual(actual, expected, [message])"
3161
Tests strict equality, as determined by the strict equality operator ( \fB===\fR )
3163
.SS "assert\.notStrictEqual(actual, expected, [message])"
3164
Tests strict non\-equality, as determined by the strict not equal operator ( \fB!==\fR )
3166
.SS "assert\.throws(block, [error], [message])"
3167
Expects \fBblock\fR to throw an error\.
3169
.SS "assert\.doesNotThrow(block, [error], [message])"
3170
Expects \fBblock\fR not to throw an error\.
3172
.SS "assert\.ifError(value)"
3173
Tests if value is not a false value, throws if it is a true value\. Useful when testing the first argument, \fBerror\fR in callbacks\.
2826
This module contains utilities for dealing with file paths. Use\fBrequire('path')\fR to use it. It provides the following methods:
2828
.SS "path.join(/<em> path1, path2, ... </em>/)"
2829
Join all arguments together and resolve the resulting path. Example:
2834
node> require('path').join(
2835
... '/foo', 'bar', 'baz/asdf', 'quux', '..')
2842
.SS "path.normalizeArray(arr)"
2843
Normalize an array of path parts, taking care of \fB'..'\fR and \fB'.'\fR parts. Example:
2848
path.normalizeArray(['',
2849
'foo', 'bar', 'baz', 'asdf', 'quux', '..'])
2851
[ '', 'foo', 'bar', 'baz', 'asdf' ]
2857
.SS "path.normalize(p)"
2858
Normalize a string path, taking care of \fB'..'\fR and \fB'.'\fR parts. Example:
2863
path.normalize('/foo/bar/baz/asdf/quux/..')
2871
.SS "path.dirname(p)"
2872
Return the directory name of a path. Similar to the Unix \fBdirname\fR command. Example:
2877
path.dirname('/foo/bar/baz/asdf/quux')
2885
.SS "path.basename(p, ext)"
2886
Return the last portion of a path. Similar to the Unix \fBbasename\fR command. Example:
2891
path.basename('/foo/bar/baz/asdf/quux.html')
2894
path.basename('/foo/bar/baz/asdf/quux.html', '.html')
2902
.SS "path.extname(p)"
2903
Return the extension of the path. Everything after the last '.' in the last portion
2904
of the path. If there is no '.' in the last portion of the path or the only '.' is
2905
the first character, then it returns an empty string. Examples:
2910
path.extname('index.html')
2913
path.extname('index')
2921
.SS "path.exists(p, callback)"
2922
Test whether or not the given path exists. Then, call the \fBcallback\fR argument with either true or false. Example:
2927
path.exists('/etc/passwd', function (exists) {
2928
sys.debug(exists ? "it's there" : "no passwd!");
3176
This module contains utilities for dealing with file paths\. Use \fBrequire(\'path\')\fR to use it\. It provides the following methods:
3178
.SS "path\.join([path1], [path2], [\.\.\.])"
3179
Join all arguments together and resolve the resulting path\.
3187
node> require(\'path\')\.join(
3188
\|\.\.\. \'/foo\', \'bar\', \'baz/asdf\', \'quux\', \'\.\.\')
3189
\'/foo/bar/baz/asdf\'
3195
.SS "path\.normalizeArray(arr)"
3196
Normalize an array of path parts, taking care of \fB\'\.\.\'\fR and \fB\'\.\'\fR parts\.
3204
path\.normalizeArray([\'\',
3205
\'foo\', \'bar\', \'baz\', \'asdf\', \'quux\', \'\.\.\'])
3207
[ \'\', \'foo\', \'bar\', \'baz\', \'asdf\' ]
3213
.SS "path\.normalize(p)"
3214
Normalize a string path, taking care of \fB\'\.\.\'\fR and \fB\'\.\'\fR parts\.
3222
path\.normalize(\'/foo/bar/baz/asdf/quux/\.\.\')
3224
\'/foo/bar/baz/asdf\'
3230
.SS "path\.dirname(p)"
3231
Return the directory name of a path\. Similar to the Unix \fBdirname\fR command\.
3239
path\.dirname(\'/foo/bar/baz/asdf/quux\')
3241
\'/foo/bar/baz/asdf\'
3247
.SS "path\.basename(p, [ext])"
3248
Return the last portion of a path\. Similar to the Unix \fBbasename\fR command\.
3256
path\.basename(\'/foo/bar/baz/asdf/quux\.html\')
3259
path\.basename(\'/foo/bar/baz/asdf/quux\.html\', \'\.html\')
3267
.SS "path\.extname(p)"
3268
Return the extension of the path\. Everything after the last \'\.\' in the last portion
3269
of the path\. If there is no \'\.\' in the last portion of the path or the only \'\.\' is
3270
the first character, then it returns an empty string\. Examples:
3275
path\.extname(\'index\.html\')
3278
path\.extname(\'index\')
3286
.SS "path\.exists(p, [callback])"
3287
Test whether or not the given path exists\. Then, call the \fBcallback\fR argument with either true or false\. Example:
3292
path\.exists(\'/etc/passwd\', function (exists) {
3293
sys\.debug(exists ? "it\'s there" : "no passwd!");
2936
This module has utilities for URL resolution and parsing.
2937
Call \fBrequire('url')\fR to use it.
3301
This module has utilities for URL resolution and parsing\.
3302
Call \fBrequire(\'url\')\fR to use it\.
2940
3305
Parsed URL objects have some or all of the following fields, depending on
2941
whether or not they exist in the URL string. Any parts that are not in the URL
2942
string will not be in the parsed object. Examples are shown for the URL
3306
whether or not they exist in the URL string\. Any parts that are not in the URL
3307
string will not be in the parsed object\. Examples are shown for the URL
2945
\fB'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'\fR
3310
\fB\'http://user:pass@host\.com:8080/p/a/t/h?query=string#hash\'\fR
2951
The full URL that was originally parsed. Example:\fB'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'\fR
3316
The full URL that was originally parsed\. Example: \fB\'http://user:pass@host\.com:8080/p/a/t/h?query=string#hash\'\fR
2957
The request protocol. Example: \fB'http:'\fR
3322
The request protocol\. Example: \fB\'http:\'\fR
2963
The full host portion of the URL, including port and authentication information. Example:\fB'user:pass@host.com:8080'\fR
3328
The full host portion of the URL, including port and authentication information\. Example: \fB\'user:pass@host\.com:8080\'\fR
2969
The authentication information portion of a URL. Example: \fB'user:pass'\fR
3334
The authentication information portion of a URL\. Example: \fB\'user:pass\'\fR
2975
Just the hostname portion of the host. Example: \fB'host.com'\fR
3340
Just the hostname portion of the host\. Example: \fB\'host\.com\'\fR
2981
The port number portion of the host. Example: \fB'8080'\fR
3346
The port number portion of the host\. Example: \fB\'8080\'\fR
2987
The path section of the URL, that comes after the host and before the query, including the initial slash if present. Example: \fB'/p/a/t/h'\fR
3352
The path section of the URL, that comes after the host and before the query, including the initial slash if present\. Example: \fB\'/p/a/t/h\'\fR
2993
The 'query string' portion of the URL, including the leading question mark. Example: \fB'?query=string'\fR
3358
The \'query string\' portion of the URL, including the leading question mark\. Example: \fB\'?query=string\'\fR
2999
Either the 'params' portion of the query string, or a querystring\-parsed object. Example:\fB'query=string'\fR or \fB{'query':'string'}\fR
3364
Either the \'params\' portion of the query string, or a querystring\-parsed object\. Example: \fB\'query=string\'\fR or \fB{\'query\':\'string\'}\fR
3005
The 'fragment' portion of the URL including the pound\-sign. Example: \fB'#hash'\fR
3370
The \'fragment\' portion of the URL including the pound\-sign\. Example: \fB\'#hash\'\fR
3010
3375
The following methods are provided by the URL module:
3012
.SS "url.parse(urlStr, parseQueryString=false)"
3013
Take a URL string, and return an object. Pass \fBtrue\fR as the second argument to also parse
3014
the query string using the \fBquerystring\fR module.
3016
.SS "url.format(urlObj)"
3017
Take a parsed URL object, and return a formatted URL string.
3019
.SS "url.resolve(from, to)"
3020
Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.
3377
.SS "url\.parse(urlStr, parseQueryString=false)"
3378
Take a URL string, and return an object\. Pass \fBtrue\fR as the second argument to also parse
3379
the query string using the \fBquerystring\fR module\.
3381
.SS "url\.format(urlObj)"
3382
Take a parsed URL object, and return a formatted URL string\.
3384
.SS "url\.resolve(from, to)"
3385
Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag\.
3022
3387
.SH "Query String"
3023
This module provides utilities for dealing with query strings. It provides the following methods:
3025
.SS "querystring.stringify(obj, sep='&', eq='=', munge=true)"
3026
Serialize an object to a query string. Optionally override the default separator and assignment characters.
3032
querystring.stringify({foo: 'bar'})
3035
querystring.stringify({foo: 'bar', baz: 'bob'}, ';', ':')
3044
By default, this function will perform PHP/Rails\-style parameter mungeing for arrays and objects used as
3045
values within \fBobj\fR.
3051
querystring.stringify({foo: 'bar', foo: 'baz', foo: 'boz'})
3053
'foo[]=bar&foo[]=baz&foo[]=boz'
3054
querystring.stringify({foo: {bar: 'baz'}})
3063
If you wish to disable the array mungeing (e.g. when generating parameters for a Java servlet), you
3064
can set the \fBmunge\fR argument to \fBfalse\fR.
3070
querystring.stringify({foo: 'bar', foo: 'baz', foo: 'boz'}, '&', '=', false)
3072
'foo=bar&foo=baz&foo=boz'
3079
Note that when \fBmunge\fR is \fBfalse\fR, parameter names with object values will still be munged.
3081
.SS "querystring.parse(str, sep='&', eq='=')"
3082
Deserialize a query string to an object. Optionally override the default separator and assignment characters.
3087
querystring.parse('a=b&b=c')
3388
This module provides utilities for dealing with query strings\. It provides the following methods:
3390
.SS "querystring\.stringify(obj, sep=\'&\', eq=\'=\', munge=true)"
3391
Serialize an object to a query string\. Optionally override the default separator and assignment characters\.
3397
querystring\.stringify({foo: \'bar\'})
3400
querystring\.stringify({foo: \'bar\', baz: \'bob\'}, \';\', \':\')
3409
By default, this function will perform PHP/Rails\-style parameter munging for arrays and objects used as
3410
values within \fBobj\fR\|\.
3416
querystring\.stringify({foo: [\'bar\', \'baz\', \'boz\']})
3418
\'foo%5B%5D=bar&foo%5B%5D=baz&foo%5B%5D=boz\'
3419
querystring\.stringify({foo: {bar: \'baz\'}})
3421
\'foo%5Bbar%5D=baz\'
3428
If you wish to disable the array munging (e\.g\. when generating parameters for a Java servlet), you
3429
can set the \fBmunge\fR argument to \fBfalse\fR\|\.
3435
querystring\.stringify({foo: [\'bar\', \'baz\', \'boz\']}, \'&\', \'=\', false)
3437
\'foo=bar&foo=baz&foo=boz\'
3444
Note that when \fBmunge\fR is \fBfalse\fR, parameter names with object values will still be munged\.
3446
.SS "querystring\.parse(str, sep=\'&\', eq=\'=\')"
3447
Deserialize a query string to an object\. Optionally override the default separator and assignment characters\.
3452
querystring\.parse(\'a=b&b=c\')
3340
The module \fBcircle.js\fR has exported the functions \fBarea()\fR and \fBcircumference()\fR. To export an object, add to the special \fBexports\fR
3341
object. (Alternatively, one can use \fBthis\fR instead of \fBexports\fR.) Variables
3342
local to the module will be private. In this example the variable \fBPI\fR is
3343
private to \fBcircle.js\fR. The function \fBputs()\fR comes from the module \fB'sys'\fR,
3344
which is a built\-in module. Modules which are not prefixed by \fB'./'\fR are
3345
built\-in module\-\-more about this later.
3348
A module prefixed with \fB'./'\fR is relative to the file calling \fBrequire()\fR.
3349
That is, \fBcircle.js\fR must be in the same directory as \fBfoo.js\fR for \fBrequire('./circle')\fR to find it.
3352
Without the leading \fB'./'\fR, like \fBrequire('assert')\fR the module is searched
3353
for in the \fBrequire.paths\fR array. \fBrequire.paths\fR on my system looks like
3357
\fB[ '/home/ryan/.node_libraries' ]\fR
3360
That is, when \fBrequire('assert')\fR is called Node looks for:
3363
1: \fB/home/ryan/.node_libraries/assert.js\fR
3366
2: \fB/home/ryan/.node_libraries/assert.node\fR
3369
3: \fB/home/ryan/.node_libraries/assert/index.js\fR
3372
4: \fB/home/ryan/.node_libraries/assert/index.node\fR
3664
The module \fBcircle\.js\fR has exported the functions \fBarea()\fR and \fBcircumference()\fR\|\. To export an object, add to the special \fBexports\fR
3665
object\. (Alternatively, one can use \fBthis\fR instead of \fBexports\fR\|\.) Variables
3666
local to the module will be private\. In this example the variable \fBPI\fR is
3667
private to \fBcircle\.js\fR\|\. The function \fBputs()\fR comes from the module \fB\'sys\'\fR,
3668
which is a built\-in module\. Modules which are not prefixed by \fB\'\./\'\fR are
3669
built\-in module\-\-more about this later\.
3672
A module prefixed with \fB\'\./\'\fR is relative to the file calling \fBrequire()\fR\|\.
3673
That is, \fBcircle\.js\fR must be in the same directory as \fBfoo\.js\fR for \fBrequire(\'\./circle\')\fR to find it\.
3676
Without the leading \fB\'\./\'\fR, like \fBrequire(\'assert\')\fR the module is searched
3677
for in the \fBrequire\.paths\fR array\. \fBrequire\.paths\fR on my system looks like
3681
\fB[ \'/home/ryan/\.node_libraries\' ]\fR
3684
That is, when \fBrequire(\'assert\')\fR is called Node looks for:
3687
1: \fB/home/ryan/\.node_libraries/assert\.js\fR
3690
2: \fB/home/ryan/\.node_libraries/assert\.node\fR
3693
3: \fB/home/ryan/\.node_libraries/assert/index\.js\fR
3696
4: \fB/home/ryan/\.node_libraries/assert/index\.node\fR
3377
interrupting once a file is found. Files ending in \fB'.node'\fR are binary Addon
3378
Modules; see 'Addons' below. \fB'index.js'\fR allows one to package a module as
3701
interrupting once a file is found\. Files ending in \fB\'\.node\'\fR are binary Addon
3702
Modules; see \'Addons\' below\. \fB\'index\.js\'\fR allows one to package a module as
3382
\fBrequire.paths\fR can be modified at runtime by simply unshifting new
3706
\fBrequire\.paths\fR can be modified at runtime by simply unshifting new
3383
3707
paths onto it, or at startup with the \fBNODE_PATH\fR environmental
3384
variable (which should be a list of paths, colon separated).
3708
variable (which should be a list of paths, colon separated)\.
3387
Addons are dynamically linked shared objects. They can provide glue to C and
3388
C++ libraries. The API (at the moment) is rather complex, involving
3711
Addons are dynamically linked shared objects\. They can provide glue to C and
3712
C++ libraries\. The API (at the moment) is rather complex, involving
3389
3713
knowledge of several libraries:
3392
V8 JavaScript, a C++ library. Used for interfacing with JavaScript:
3393
creating objects, calling functions, etc. Documented mostly in the\fBv8.h\fR header file (\fBdeps/v8/include/v8.h\fR in the Node source tree).
3716
V8 JavaScript, a C++ library\. Used for interfacing with JavaScript:
3717
creating objects, calling functions, etc\. Documented mostly in the \fBv8\.h\fR header file (\fBdeps/v8/include/v8\.h\fR in the Node source tree)\.
3396
libev, C event loop library. Anytime one needs to wait for a file
3720
libev, C event loop library\. Anytime one needs to wait for a file
3397
3721
descriptor to become readable, wait for a timer, or wait for a signal to
3398
received one will need to interface with libev. That is, if you perform
3399
any I/O, libev will need to be used. Node uses the \fBEV_DEFAULT\fR event
3400
loop. Documentation can be found http:/cvs.schmorp.de/libev/ev.html[here].
3403
libeio, C thread pool library. Used to execute blocking POSIX system
3404
calls asynchronously. Mostly wrappers already exist for such calls, in\fBsrc/file.cc\fR so you will probably not need to use it. If you do need it,
3405
look at the header file \fBdeps/libeio/eio.h\fR.
3408
Internal Node libraries. Most importantly is the \fBnode::ObjectWrap\fR
3409
class which you will likely want to derive from.
3412
Others. Look in \fBdeps/\fR for what else is available.
3722
received one will need to interface with libev\. That is, if you perform
3723
any I/O, libev will need to be used\. Node uses the \fBEV_DEFAULT\fR event
3724
loop\. Documentation can be found http:/cvs\.schmorp\.de/libev/ev\.html[here]\.
3727
libeio, C thread pool library\. Used to execute blocking POSIX system
3728
calls asynchronously\. Mostly wrappers already exist for such calls, in \fBsrc/file\.cc\fR so you will probably not need to use it\. If you do need it,
3729
look at the header file \fBdeps/libeio/eio\.h\fR\|\.
3732
Internal Node libraries\. Most importantly is the \fBnode::ObjectWrap\fR
3733
class which you will likely want to derive from\.
3736
Others\. Look in \fBdeps/\fR for what else is available\.
3417
Node statically compiles all its dependencies into the executable. When
3418
compiling your module, you don't need to worry about linking to any of these
3741
Node statically compiles all its dependencies into the executable\. When
3742
compiling your module, you don\'t need to worry about linking to any of these
3422
To get started let's make a small Addon which does the following except in
3746
To get started let\'s make a small Addon which does the following except in
3428
exports.hello = 'world';
3752
exports\.hello = \'world\';
3435
To get started we create a file \fBhello.cc\fR:
3759
To get started we create a file \fBhello\.cc\fR:
3441
3765
using namespace v8;
3443
init (Handle<Object> target)
3767
init (Handle<Object> target)
3445
3769
HandleScope scope;
3446
3770
target\->Set(String::New("hello"), String::New("World"));