一个用 Node 编写的简单响应 'Hello World' 的Web 服务器示例:
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
将以上代码保存到example.js
,运行以下命令来启动服务器:
> node example.js
Server running at http://127.0.0.1:8124/
文档中所有示例都能这样运行。
这些对象在任何作用域下都可以访问。
全局的命名空间对象。
在浏览器中,全局作用域是顶级作用域。这意味着在浏览器的全局作用域下var something
会定义一个全局变量。在 Node 里,顶级作用域不是全局的,在一个 Node 模块的顶级作用域中 var something
只会定义一个该模块的局部变量。
进程对象。
引用模块。请参考 '模块' 章节。
使用内置的require()
机制来查询模块路径。不载入模块,仅返回解析好的文件名。
require()
使用的搜索路径数组,可以自由修改它。
示例:添加一个新路径到搜索列表的头部
require.paths.unshift('/usr/local/node');
正在运行的脚本文件名。它是脚本的绝对路径,不一定和命令行参数的文件名相同。
示例:从 /Users/mjr
运行 node example.js
console.log(__filename);
// /Users/mjr/example.js
正在运行的脚本所在目录。
示例:从 /Users/mjr
运行 node example.js
console.log(__dirname);
// /Users/mjr
当前模块的引用。特别地,module.exports
其实就是 exports
对象。更多信息请参考 src/node.js
。
设定 callback
在 delay
毫秒之后执行。返回供 clearTimeout()
使用的
timeoutId
。还可以给回调函数传递参数(可选)。
清除定时器。
设定 callback
每 delay
毫秒执行一次。返回供 clearInterval()
使用的
intervalId
。还可以给回调函数传递参数(可选)。
停止定期执行。
Node 使用 CommonJS 模块系统。
Node 有一个简单的模块加载系统。在 Node 中,文件和模块一一对应。比如,在 foo.js
加载同一目录中的 circle.js
模块。
foo.js
的内容:
var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is '
+ circle.area(4));
circle.js
的内容:
var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
模块 circle.js
导出了 area()
函数和 circumference()
函数,这样它们就能从模块外部访问了。要导出对象,将其添加到特殊的 exports
对象就行。
模块的局部变量是私有的。在本例中,变量 PI
是 circle.js
私有的。
Node 有一些已编译成二进制的模块,这些模块将在本文档的其他地方详细介绍。
核心模块在 Node 源代码的 lib/
文件夹中定义。
使用 require()
时,核心模块总是优先加载。例如,require('http')
总是返回内置的 HTTP 模块,即使该名称的文件存在。
如果没有找到确切的文件,Node 将尝试给所需的文件名添加 .js
后缀再加载,然后再尝试 .node
。
.js
文件被视为 JavaScript 文本文件,而 .node
文件被视为已编译的插件模块,用 dlopen
加载。
模块以 '/'
开头表示使用文件的绝对路径。例如,require('/home/marco/foo.js')
将加载 /home/marco/foo.js
文件。
模块以 './'
开头表示调用 require()
时使用相对路径。也就是说,为了保证 require('./circle')
能找到,circle.js
必须和 foo.js
在同一目录。
如果不以 '/' 或'./' 开头,该模块可以是一个“核心模块”,也可是一个从 node_modules
文件夹中加载的模块。
如果传递给 require()
有模块标识符是不是原生模块,而且不以 '/'
、'../'
或'./'
开头,那么 Node 从当前模块的父目录+/node_modules
这个位置尝试加载。
如果还是没有找到,那么它跳到上层目录并依此类推,直到找到模块,或者达到根目录为止。
例如,如果在文件 '/home/ry/projects/foo.js'
中调用 require('bar.js')
,那么 Node 将在下列位置查找,顺序如下:
/home/ry/projects/node_modules/bar.js
/home/ry/node_modules/bar.js
/home/node_modules/bar.js
/node_modules/bar.js
这就允许程序将依赖关系本地化,防止它们冲突。
当嵌套依赖关系的层次很深时,这个文件查找列表可能会变得很长。因此,在查找时进行如下优化:
首先,/node_modules
不会附加到一个以 /node_modules
结尾的文件夹后面。
其次,如果调用 require()
的文件已经在一个 node_modules
层级里,那么最顶层的 node_modules
文件夹将被视为搜索树的根。
例如,如果在文件 '/home/ry/projects/foo/node_modules/bar/node_modules/baz/quux.js'
中调用 require('asdf.js')
,那么 Node 将搜索下列位置:
/home/ry/projects/foo/node_modules/bar/node_modules/baz/node_modules/asdf.js
/home/ry/projects/foo/node_modules/bar/node_modules/asdf.js
/home/ry/projects/foo/node_modules/asdf.js
Node 允许用户在独立的目录中方便地组织程序,然后提供单一入口指向该库。有三种方式可以将文件夹作为 require()
的参数。
第一种方式是在该文件夹中创建 package.json
文件,指定一个 main
模块。一个典型的 package.json 文件可能看起来像这样:
{ "name" : "some-library",
"main" : "./lib/some-library.js" }
如果此文件位于 ./some-library
文件夹,则 require('./some-library')
会尝试加载 ./some-library/lib/some-library.js
。
这是 Node 能找到 package.json 文件的情况。
如果在该目录中没有 package.json 文件,那么 Node 将尝试加载该目录中的 index.js
或 index.node
文件。例如,如果上面的例子找不到 package.json,那么 require('./some-library')
将试图加载:
./some-library/index.js
./some-library/index.node
模块在首次被加载后会缓存起来。这意味着每次调用 require('foo')
将得到完全相同的对象,如果它被解析为同一个文件的话。
为了得到调用 require()
时被载入的确切的文件名,使用 require.resolve()
函数。
综上所述,这是 require.resolve 的伪码描述:
require(X)
1. If X is a core module,
a. return the core module
b. STOP
2. If X begins with `./` or `/`,
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"
LOAD_AS_FILE(X)
1. If X is a file, load X as JavaScript text. STOP
2. If X.js is a file, load X.js as JavaScript text. STOP
3. If X.node is a file, load X.node as binary addon. STOP
LOAD_AS_DIRECTORY(X)
1. If X/package.json is a file,
a. Parse X/package.json, and look for "main" field.
b. let M = X + (json main field)
c. LOAD_AS_FILE(M)
2. LOAD_AS_FILE(X/index)
LOAD_NODE_MODULES(X, START)
1. let DIRS=NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
a. LOAD_AS_FILE(DIR/X)
b. LOAD_AS_DIRECTORY(DIR/X)
NODE_MODULES_PATHS(START)
1. let PARTS = path split(START)
2. let ROOT = index of first instance of "node_modules" in PARTS, or 0
3. let I = count of PARTS - 1
4. let DIRS = []
5. while I > ROOT,
a. if PARTS[I] = "node_modules" CONTINUE
c. DIR = path join(PARTS[0 .. I] + "node_modules")
b. DIRS = DIRS + DIR
6. return DIRS
在 Node 中,require.paths
是一个字符串数组,表示模块不以 '/'
'./'
或 '..'
打头的搜索路径。例如,如果 require.paths 设置为:
[ '/home/micheil/.node_modules',
'/usr/local/lib/node_modules' ]
则调用 require('bar/baz.js')
会搜索以下位置:
'/home/micheil/.node_modules/bar/baz.js'
'/usr/local/lib/node_modules/bar/baz.js'
可以在运行时修改 require.paths
数组来改变这种行为。
它的值最初从 NODE_PATH
环境变量而来,那是一个冒号分隔的绝对路径列表。在前面的例子中,NODE_PATH
环境变量可能被设置为:
/home/micheil/.node_modules:/usr/local/lib/node_modules
只有使用上面的 node_modules
算法找不到模块时才会尝试 require.paths
。全局模块的优先级低于捆绑依赖。
出于兼容性的考虑,require.paths
仍然是模块查找过程的首选策略。尽管如此,它可能会在将来的版本中废弃。
虽然它看起来似乎是个好主意,但在实践中一个可变的 require.paths
列表往往是麻烦和混乱的根源。
这行代码并不会像期望的那样:
require.paths = [ '/usr/lib/node' ];
它的结果就是丢弃了 Node 实际的模块查找路径引用,并创建了一个毫无用处的指向别处的新的引用。
如果你这样做:
require.paths.push('./lib');
它不会添加 ./lib
在文件系统上已解析的完整路径。相反,它实际增加的是 './lib'
,这意味着如果你在 /a/b/x.js
中 require('y.js')
,那么它会查找 /a/b/lib/y.js
。如果你之后又在 /l/m/n/o/p.js
中 require('y.js')
,那么它就会查找 /l/m/n/o/lib/y.js
。
在实践中,人们往往将它作为捆绑依赖的临时解决办法,这个技巧是不太稳妥的。
有一种糟糕的设计:所有模块共用一个 require.paths
数组。
结果,如果一个 Node 程序依赖于这种行为,它可能会永久而微妙地改变同一进程中其它 Node 程序的行为。当应用程序的复杂度增加时,我们倾向于封装功能,这些行为很难预料的部分会成为开发者的恶梦。
在 Node 中,require()
函数的语义被设计成通用性足以支持大量合理的目录结构。因此 dpkg
、rpm
和 npm
之类的包管理器可以从 Node 模块构建原生包而不作更改。
下面我们给出一个可以工作的建议的目录结构:
比方说,我们希望 /usr/lib/node/<some-package>/<some-version>
文件夹中包含某个包的特定版本的内容。
一个软件包可以依赖别的包。为了安装 foo
包,你可能需要安装 bar
包的特定版本 。可能该 bar
包本身有依赖关系,在某些情况下,这些依赖关系甚至可能发生冲突或者形成回路。
由于 Node 在加载任何模块时都会查找它的真实路径
(即:会解析符号链接),然后在 node_modules
文件夹用上文描述的方式查找依赖。使用以下架构可以很简单地解决:
/usr/lib/node/foo/1.2.3/
-foo
包的内容,版本1.2.3。/usr/lib/node/bar/4.3.2/
-bar
包的内容,foo
依赖这个包。/usr/lib/node/foo/1.2.3/node_modules/bar
-到 /usr/lib/node/bar/4.3.2/
的符号链接。/usr/lib/node/bar/4.3.2/node_modules/*
-到 bar
所依赖的包的符号链接。因此,即使遇到一个回路,或者有依赖冲突,每个模块都能够得到它依赖的可用版本。
当 foo
包中有代码 require('bar')
时,它会得到符号链接至 /usr/lib/node/foo/1.2.3/node_modules/bar
的版本。然后,当 bar
包调用 require('quux')
时,它会得到符号链接至 /usr/lib/node/bar/4.3.2/node_modules/quux
的版本。
此外,为了使模块查找过程更加优化,而不是直接把包放到 /usr/lib/node
中,我们可以它们放到 /usr/lib/node_modules/<name>/<version>
里。这样,Node 就不用在 /usr/node_modules
或 /node_modules
中查找了。
为了使 REPL 能够正常引用模块,可以将 /usr/lib/node_modules
添加至 $NODE_PATH
环境变量。因为使用 node_modules
文件夹查找模块时的路径都是相对的,而且调用 require()
时基于文件的真实路径,因此软件包本身可以放在任何位置。
Addons are dynamically linked shared objects. They can provide glue to C and C++ libraries. The API (at the moment) is rather complex, involving knowledge of several libraries:
V8 JavaScript, a C++ library. Used for interfacing with JavaScript:
creating objects, calling functions, etc. Documented mostly in the
v8.h
header file (deps/v8/include/v8.h
in the Node source tree).
libev, C event loop library. Anytime one needs to wait for a file
descriptor to become readable, wait for a timer, or wait for a signal to
received one will need to interface with libev. That is, if you perform
any I/O, libev will need to be used. Node uses the EV_DEFAULT
event
loop. Documentation can be found here.
libeio, C thread pool library. Used to execute blocking POSIX system
calls asynchronously. Mostly wrappers already exist for such calls, in
src/file.cc
so you will probably not need to use it. If you do need it,
look at the header file deps/libeio/eio.h
.
Internal Node libraries. Most importantly is the node::ObjectWrap
class which you will likely want to derive from.
Others. Look in deps/
for what else is available.
Node statically compiles all its dependencies into the executable. When compiling your module, you don't need to worry about linking to any of these libraries.
To get started let's make a small Addon which does the following except in C++:
exports.hello = 'world';
To get started we create a file hello.cc
:
#include <v8.h>
using namespace v8;
extern "C" void
init (Handle<Object> target)
{
HandleScope scope;
target->Set(String::New("hello"), String::New("world"));
}
This source code needs to be built into hello.node
, the binary Addon. To
do this we create a file called wscript
which is python code and looks
like this:
srcdir = '.'
blddir = 'build'
VERSION = '0.0.1'
def set_options(opt):
opt.tool_options('compiler_cxx')
def configure(conf):
conf.check_tool('compiler_cxx')
conf.check_tool('node_addon')
def build(bld):
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
obj.target = 'hello'
obj.source = 'hello.cc'
Running node-waf configure build
will create a file
build/default/hello.node
which is our Addon.
node-waf
is just WAF, the python-based build system. node-waf
is
provided for the ease of users.
All Node addons must export a function called init
with this signature:
extern 'C' void init (Handle<Object> target)
For the moment, that is all the documentation on addons. Please see https://github.com/ry/node_postgres for a real example.
process
对象是一个全局对象,能从任何地方访问。它也是 EventEmitter
的实例。
function () {}
进程即将退出的时候触发。它是放置检查模块状态(比如单元测试)钩子的好地方,主事件循环在 'exit' 回调完成后就不再执行,因此记时器可能不会生效。
示例:监听 exit
事件
process.on('exit', function () {
process.nextTick(function () {
console.log('不会执行到这里。');
});
console.log('即将退出。');
});
function (err) { }
当一个异常冒泡至主事件循环(即该事件未被捕获)时触发。如果监听了此事件,默认动作(打印错误堆栈并退出)不会被执行。
示例:监听 uncaughtException
事件
process.on('uncaughtException', function (err) {
console.log('捕获到异常:' + err);
});
setTimeout(function () {
console.log('这里仍然会执行。');
}, 500);
// 故意制造一个异常,不捕获它
nonexistentFunc();
console.log('这里就不会执行了。');
注意:uncaughtException
是一种非常原始的异常处理机制,在程序中使用 try / catch 能更好地控制流程。对于服务器上需要长期运行的程序来说,uncaughtException
是一个很有用的安全机制。
function () {}
进行收到信号时触发。参考 sigaction(2) 以获取SIGINT, SIGUSR1 之类的标准 POSIX 信号列表。
救命:监听 SIGINT
事件
// 开始从标准输入读取数据,所以不会立即退出
process.stdin.resume();
process.on('SIGINT', function () {
console.log('收到 SIGINT 信号,按 Control+D 退出。');
});
想要向进程发送 SIGINT
信号,比较简单的办法是按 Control+C
(大多数终端程序都支持)。
一个代表 stdout
的 Writable Stream
。
示例:console.log
的定义
console.log = function (d) {
process.stdout.write(d + '\n');
};
一个代表 stderr
的可写流(Writable Stream)。对这个流的写操作是阻塞的。
一个代表 stdin
的 Readable Stream
。标准输入流默认是暂停的,所以你必须调用 process.stdin.resume()
来读取 stdin
。
示例:打开标准输入并监听事件
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
process.stdout.write('data: ' + chunk);
});
process.stdin.on('end', function () {
process.stdout.write('end');
});
一个包含命令行参数的数组。第一个元素是 'node',第二个是 JavaScript 文件名,接下来是附加的命令行参数。
// 打印 process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
运行结果:
$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four
启动本进程的 node 可执行文件所在的绝对路径。
示例:
/usr/local/bin/node
更改进程当前的工作目录,如果失败则抛出异常。
console.log('初始工作目录:' + process.cwd());
try {
process.chdir('/tmp');
console.log('新的工作目录:' + process.cwd());
}
catch (err) {
console.log('chdir: ' + err);
}
返回进程当前的工作目录。
console.log('Current directory: ' + process.cwd());
一个包含用户环境变量的对象。参考 environ(7)。
以指定的退出代码 code
终止进程。如果省此参数,使用代表 '成功' 的代码 0
退出。
使用代表 '失败' 的代码退出:
process.exit(1);
运行 node 的 shell 应该可以得到退出代码为 1。
获取进程的组ID,参考 getgid(2)。它是一个数字ID,不是组名。
console.log('Current gid: ' + process.getgid());
设置进程的组ID,参考 setgid(2)。组ID(数字)或者组名(字符串)都接受。如果指定的是组名,本方法会因解析组名而阻塞。
console.log('Current gid: ' + process.getgid());
try {
process.setgid(501);
console.log('New gid: ' + process.getgid());
}
catch (err) {
console.log('Failed to set gid: ' + err);
}
获取进程的用户ID,参考 getuid(2)。它是一个数字ID,不是用户名。
console.log('Current uid: ' + process.getuid());
设置进程的用户ID,参考 setuid(2)。用户ID(数字)或者用户名(字符串)都接受。如果指定的是用户名,本方法会因解析用户名而阻塞。
console.log('Current uid: ' + process.getuid());
try {
process.setuid(501);
console.log('New uid: ' + process.getuid());
}
catch (err) {
console.log('Failed to set uid: ' + err);
}
进程版本,即 NODE_VERSION
。
console.log('Version: ' + process.version);
安装路径,即 NODE_PREFIX
。
console.log('Prefix: ' + process.installPrefix);
向目标进程发送信号。pid
为目标进程ID,signal
为信号名称。信号名称为类似 'SIGINT' 或 'SIGUSR1' 的字符串,如果省略,默认为 'SIGTERM'(参考 kill(2))。
注意:尽管本方法名为 process.kill
,但它只用来发送信号,像 kill
系统调用那样。发送信号除了结束目标进程,还能做其它事情。
示例:给自己发送一个信号
process.on('SIGHUP', function () {
console.log('收到 SIGHUP 信号。');
});
setTimeout(function () {
console.log('正在退出……');
process.exit(0);
}, 100);
process.kill(process.pid, 'SIGHUP');
进程的 PID。
console.log('进程的 PID 是:' + process.pid);
获取/设置 'ps' 命令中显示的名称。
运行在哪个平台上。如 'linux2'
,'darwin'
,等等。
console.log('This platform is ' + process.platform);
返回一个描述 Node 进程内存使用情况的对象。
var util = require('util');
console.log(util.inspect(process.memoryUsage()));
This will generate:
{ rss: 4935680,
vsize: 41893888,
heapTotal: 1826816,
heapUsed: 650472 }
heapTotal
和 heapUsed
代表 V8 占用的内存。
在下一轮事件循环中调用这个回调函数。它不是 setTimeout(fn, 0)
的别名,它要高效得多。
process.nextTick(function () {
console.log('nextTick callback');
});
设置或读取进程的文件创建模式掩码,子进程会从父进程继承这个掩码。如果指定了 mask
参数,则返回旧的掩码,否则返回当前掩码。
这些函数属于 'util'
模块。使用 require('util')
来访问它们。
同步输出。将阻塞进程并立即向 stderr
输出 string
。
require('util').debug('message on stderr');
向 stdout
输出 string
和时间戳 。
require('util').log('Timestmaped message.');
返回 object
的字符串表示,用于调试。
如果 showHidden
为 true
,那么对象不可枚举的属性也会显示。
如果提供了 depth
,它将指定 inspect
需要递归多少层,在查看复杂对象时很有用。
默认只递归两层。如果要无限递归,给 depth
传 null
。
示例:查看 util
对象的所有属性
var util = require('util');
console.log(util.inspect(util, true, null));
本函数属于实验性质。
从 readableStream
读取数据,并将其发送到 writableStream
。当 writableStream.write(data)
返回 false
时 readableStream
将被暂停,直到 writableStream
触发 drain
事件。callback
只接受一个 error 参数,在 writableStream
关闭或发生错误时调用。
从 构造函数 继承原型方法。constructor
的原型将被设置成一个从 superConstructor
创建的新对象。
为了更加方便使用,可以通过 constructor.super_
来 访问 superConstructor
。
Node 中很多对象都会触发事件:net.Server
在每次建立新连接时触发事件,fs.readStream
在文件打开时触发事件。所有能触发事件的对象都是 events.EventEmitter
的实例。您可以通过 require("events");
来访问此模块。
事件名称通常由驼峰式字符串表示,但这并不是强制要求,因为任何字符串都可以用作事件名称。
函数可以附加到对象,然后在事件触发时执行。这些函数被称为 监听器(listener)。
要访问 EventEmitter 类, 请 require('events').EventEmitter
。
当一个 EventEmitter
的实例遇到错误时,典型的动作是触发一个 'error'
事件。在 Node 中,错误事件被视为特殊情况,如果没有监听它,默认会打印一个错误堆栈并退出程序。
所有 EventEmitter 的实例在添加新的监听器时都会触发 'newListener'
事件。
给指定事件添加新的监听器,添加后位于监听器数组末端。
server.on('connection', function (stream) {
console.log('someone connected!');
});
给事件监听器一次 。该监听器仅在事件被触发后调用一次,然后它会被删除。
server.once('connection', function (stream) {
console.log('Ah, we have our first user!');
});
从指定事件的监听器数组删除单个监听器。注意:会改变该监听器数组的索引。
var callback = function(stream) {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
删除指定事件的所有监听器。
默认情况下,添加超过 10 个监听器时 EventEmitters 会打印一条警告信息。这个默认设置有助于发现内存泄漏。显然,10 个监听器不一定够用,此函数允许放宽这一限制。设置为 0 表示不作限制。
返回指定事件的监听器数组。该数组可以在运行时操作,比如删除监听器。
server.on('connection', function (stream) {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')); // [ [Function] ]
用提供的参数按(数组中的)顺序执行监听器。
function (event, listener) { }
添加新的监听器时触发此事件。
Pure Javascript is Unicode friendly but not nice to binary data. When dealing with TCP streams or the file system, it's necessary to handle octet streams. Node has several strategies for manipulating, creating, and consuming octet streams.
Raw data is stored in instances of the Buffer
class. A Buffer
is similar
to an array of integers but corresponds to a raw memory allocation outside
the V8 heap. A Buffer
cannot be resized.
The Buffer
object is global.
Converting between Buffers and JavaScript string objects requires an explicit encoding method. Here are the different string encodings;
'ascii'
- for 7 bit ASCII data only. This encoding method is very fast, and will
strip the high bit if set.
'utf8'
- Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.
'ucs2'
- 2-bytes, little endian encoded Unicode characters. It can encode
only BMP(Basic Multilingual Plane, U+0000 - U+FFFF).
'base64'
- Base64 string encoding.
'binary'
- A way of encoding raw binary data into strings by using only
the first 8 bits of each character. This encoding method is deprecated and
should be avoided in favor of Buffer
objects where possible. This encoding
will be removed in future versions of Node.
Allocates a new buffer of size
octets.
Allocates a new buffer using an array
of octets.
Allocates a new buffer containing the given str
.
Writes string
to the buffer at offset
using the given encoding. Returns
number of octets written. If buffer
did not contain enough space to fit
the entire string, it will write a partial amount of the string. In the case
of 'utf8'
encoding, the method will not write partial characters.
Example: write a utf8 string into a buffer, then print it
buf = new Buffer(256);
len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(len + " bytes: " + buf.toString('utf8', 0, len));
// 12 bytes: ½ + ¼ = ¾
Decodes and returns a string from buffer data encoded with encoding
beginning at start
and ending at end
.
See buffer.write()
example, above.
Get and set the octet at index
. The values refer to individual bytes,
so the legal range is between 0x00
and 0xFF
hex or 0
and 255
.
Example: copy an ASCII string into a buffer, one byte at a time:
str = "node.js";
buf = new Buffer(str.length);
for (var i = 0; i < str.length ; i++) {
buf[i] = str.charCodeAt(i);
}
console.log(buf);
// node.js
Tests if obj
is a Buffer
.
Gives the actual byte length of a string. This is not the same as
String.prototype.length
since that returns the number of characters in a
string.
Example:
str = '\u00bd + \u00bc = \u00be';
console.log(str + ": " + str.length + " characters, " +
Buffer.byteLength(str, 'utf8') + " bytes");
// ½ + ¼ = ¾: 9 characters, 12 bytes
The size of the buffer in bytes. Note that this is not necessarily the size
of the contents. length
refers to the amount of memory allocated for the
buffer object. It does not change when the contents of the buffer are changed.
buf = new Buffer(1234);
console.log(buf.length);
buf.write("some string", "ascii", 0);
console.log(buf.length);
// 1234
// 1234
Does a memcpy() between buffers.
Example: build two Buffers, then copy buf1
from byte 16 through byte 19
into buf2
, starting at the 8th byte in buf2
.
buf1 = new Buffer(26);
buf2 = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97; // 97 is ASCII a
buf2[i] = 33; // ASCII !
}
buf1.copy(buf2, 8, 16, 20);
console.log(buf2.toString('ascii', 0, 25));
// !!!!!!!!qrst!!!!!!!!!!!!!
Returns a new buffer which references the
same memory as the old, but offset and cropped by the start
and end
indexes.
Modifying the new buffer slice will modify memory in the original buffer!
Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte from the original Buffer.
数据流是 Node 中很多对象都有实现的一个抽象接口。例如,一个到 HTTP 服务器的请求就是数据流,标准输出(stdout)也是。有些数据流可读,有些可写,有些可以同时读写。所有数据流都是 EventEmitter
的实例。
一个 Readable Stream
有如下的方法、成员和事件。
function (data) { }
触发 'data'
事件时,传进来的参数可能是一个 Buffer
(默认),也可能是字符串(如果使用了 setEncoding()
的话)。
function () { }
当数据流收到一个 EOF(在 TCP 的术语中叫做 FIN)时触发。意味着不会再有 'data'
事件(没数据)了。如果数据流同时可写,则它还可以继续写入。
function (exception) { }
接收数据出错时触发。
function () { }
底层的文件描述符被关闭时触发。不是所有数据流都会触发此事件。(例如,新进的 HTTP 请求就不会触发 'close'
。)
function (fd) { }
数据流收到文件描述符信息时触发。只有 UNIX 数据流支持,其它数据流不会触发。
一个布尔值,默认为 true
,数据流出错、到达末尾、或者调用了 destroy()
后,该值为 false
。
使 data 事件返回字符串而不是 Buffer
对象。encoding
可以是 'utf8'
,'ascii'
或 'base64'
。
暂停触发 'data'
事件。
从暂停状态恢复触发 'data'
事件。
关闭底层的文件描述符。数据流将不再触发任何事件。
等写入队列处理完毕再关闭文件描述符。
这是 Stream.prototype
的方法,所有 Stream
都可使用。
连接到可写目标数据流 destination
,本数据流传入的数据将写入 destination
。目标和源将通过必要的暂停或恢复操作来保持同步。
模拟 Unix cat
命令:
process.stdin.resume();
process.stdin.pipe(process.stdout);
源触发 end
事件时,目标默认会调用 end()
,因此 destination
不再可写。传入 { end: false }
作为 options
参数以确保目标数据流不被关闭。
这将使 process.stdout
保持打开状态,标准输入关闭后还能向标准输出写入“Goodbye”:
process.stdin.resume();
process.stdin.pipe(process.stdout, { end: false });
process.stdin.on("end", function() {
process.stdout.write("Goodbye\n");
});
注意:如果源数据流不支持 pause()
和 resume()
,此函数将给源数据流添加简单的 pause()
和 resume()
定义:仅触发 'pause'
和 'resume'
事件。
Writable Stream
有如下的方法、成员和事件:
function () { }
在 write()
方法被调用并返回 false
后触发,表示它可以安全地再次写入。
function (exception) { }
出错时触发,生成 exception
异常。
function () { }
底层文件描述符被关闭时触发。
function (src) { }
该数据流被传入另一可读数据流的 pipe 方法时触发。
一个布尔值,默认为 true
,出错或者调用 end()
/ destroy()
之后变成 false
。
以给定的 encoding
编码向数据流写入字符串 string
。如果字符串成功写到到内核缓冲区则返回 true
。返回 false
说明内核缓冲区已满,数据将延迟发送。'drain'
事件意味着内核缓冲区又为空(可写)了。encoding
默认为 'utf8'
。
如果指定了可选的 fd
参数,它将被当作以流的形式来发送的整形文件描述符。只支持 UNIX 数据流,否则会忽略而不作任何提示。当以这种方式发送文件描述符时,在数据流写入队列清空前关闭文件描述符会导致发送无效(已关闭)文件描述符。
同上,区别在于使用 Buffer 对象。
通过 EOF 或 FIN 来终止数据流。
以给定的 encoding
编码发送 string
,并通过 FIN 或 EOF 来终止数据流。这将减少数据包的发送数量。
同上,区别在于使用 Buffer
对象。
关闭底层的文件描述符。数据流将不再触发任何事件。
等写入队列清空后再关闭文件描述符。如果写入队列中没有数据,destroySoon()
将被直接摧毁。
Use require('crypto')
to access this module.
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.
It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.
Creates a credentials object, with the optional details being a dictionary with keys:
key
: a string holding the PEM encoded private keycert
: a string holding the PEM encoded certificateca
: either a string or list of strings of PEM encoded CA certificates to trust.If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.
Creates and returns a hash object, a cryptographic hash with the given algorithm which can be used to generate hash digests.
algorithm
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, openssl list-message-digest-algorithms
will display the available digest algorithms.
Updates the hash content with the given data
.
This can be called many times with new data as it is streamed.
Calculates the digest of all of the passed data to be hashed.
The encoding
can be 'hex'
, 'binary'
or 'base64'
.
Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.
algorithm
is dependent on the available algorithms supported by OpenSSL - see createHash above.
key
is the hmac key to be used.
Update the hmac content with the given data
.
This can be called many times with new data as it is streamed.
Calculates the digest of all of the passed data to the hmac.
The encoding
can be 'hex'
, 'binary'
or 'base64'
.
Creates and returns a cipher object, with the given algorithm and key.
algorithm
is dependent on OpenSSL, examples are 'aes192'
, etc.
On recent releases, openssl list-cipher-algorithms
will display the available cipher algorithms.
Updates the cipher with data
, the encoding of which is given in input_encoding
and can be 'utf8'
, 'ascii'
or 'binary'
. The output_encoding
specifies
the output format of the enciphered data, and can be 'binary'
, 'base64'
or 'hex'
.
Returns the enciphered contents, and can be called many times with new data as it is streamed.
Returns any remaining enciphered contents, with output_encoding
being one of: 'binary'
, 'ascii'
or 'utf8'
.
Creates and returns a decipher object, with the given algorithm and key. This is the mirror of the cipher object above.
Updates the decipher with data
, which is encoded in 'binary'
, 'base64'
or 'hex'
.
The output_decoding
specifies in what format to return the deciphered plaintext: 'binary'
, 'ascii'
or 'utf8'
.
Returns any remaining plaintext which is deciphered,
with output_encoding' being one of:
'binary',
'ascii' or
'utf8'`.
Creates and returns a signing object, with the given algorithm.
On recent OpenSSL releases, openssl list-public-key-algorithms
will display
the available signing algorithms. Examples are 'RSA-SHA256'
.
Updates the signer object with data. This can be called many times with new data as it is streamed.
Calculates the signature on all the updated data passed through the signer.
private_key
is a string containing the PEM encoded private key for signing.
Returns the signature in output_format
which can be 'binary'
, 'hex'
or 'base64'
.
Creates and returns a verification object, with the given algorithm. This is the mirror of the signing object above.
Updates the verifier object with data. This can be called many times with new data as it is streamed.
Verifies the signed data by using the cert
which is a string containing
the PEM encoded public key, and signature
, which is the previously calculates
signature for the data, in the signature_format
which can be 'binary'
, 'hex'
or 'base64'
.
Returns true or false depending on the validity of the signature for the data and public key.
Use require('tls')
to access this module.
The tls
module uses OpenSSL to provide Transport Layer Security and/or
Secure Socket Layer: encrypted stream communication.
TLS/SSL is a public/private key infrastructure. Each client and each server must have a private key. A private key is created like this
openssl genrsa -out ryans-key.pem 1024
All severs and some clients need to have a certificate. Certificates are public keys signed by a Certificate Authority or self-signed. The first step to getting a certificate is to create a "Certificate Signing Request" (CSR) file. This is done with:
openssl req -new -key ryans-key.pem -out ryans-csr.pem
To create a self-signed certificate with the CSR, do this:
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
Alternatively you can send the CSR to a Certificate Authority for signing.
(TODO: docs on creating a CA, for now interested users should just look at
test/fixtures/keys/Makefile
in the Node source code)
Creates a new client connection to the given port
and host
. (If host
defaults to localhost
.) options
should be an object which specifies
key
: A string or Buffer
containing the private key of the server in
PEM format. (Required)
cert
: A string or Buffer
containing the certificate key of the server in
PEM format.
ca
: An array of strings or Buffer
s of trusted certificates. If this is
omitted several well known "root" CAs will be used, like VeriSign.
These are used to authorize connections.
tls.connect()
returns a cleartext CryptoStream
object.
After the TLS/SSL handshake the callback
is called. The callback
will be
called no matter if the server's certificate was authorized or not. It is up
to the user to test s.authorized
to see if the server certificate was
signed by one of the specified CAs. If s.authorized === false
then the error
can be found in s.authorizationError
.
This class is a subclass of net.Server
and has the same methods on it.
Instead of accepting just raw TCP connections, this accepts encrypted
connections using TLS or SSL.
Here is a simple example echo server:
var tls = require('tls');
var fs = require('fs');
var options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
};
tls.createServer(options, function (s) {
s.write("welcome!\n");
s.pipe(s);
}).listen(8000);
You can test this server by connecting to it with openssl s_client
:
openssl s_client -connect 127.0.0.1:8000
This is a constructor for the tls.Server
class. The options object
has these possibilities:
key
: A string or Buffer
containing the private key of the server in
PEM format. (Required)
cert
: A string or Buffer
containing the certificate key of the server in
PEM format. (Required)
ca
: An array of strings or Buffer
s of trusted certificates. If this is
omitted several well known "root" CAs will be used, like VeriSign.
These are used to authorize connections.
requestCert
: If true
the server will request a certificate from
clients that connect and attempt to verify that certificate. Default:
false
.
rejectUnauthorized
: If true
the server will reject any connection
which is not authorized with the list of supplied CAs. This option only
has an effect if requestCert
is true
. Default: false
.
function (cleartextStream) {}
This event is emitted after a new connection has been successfully
handshaked. The argument is a duplex instance of stream.Stream
. It has all
the common stream methods and events.
cleartextStream.authorized
is a boolean value which indicates if the
client has verified by one of the supplied certificate authorities for the
server. If cleartextStream.authorized
is false, then
cleartextStream.authorizationError
is set to describe how authorization
failed. Implied but worth mentioning: depending on the settings of the TLS
server, you unauthorized connections may be accepted.
Begin accepting connections on the specified port
and host
. If the
host
is omitted, the server will accept connections directed to any
IPv4 address (INADDR_ANY
).
This function is asynchronous. The last parameter callback
will be called
when the server has been bound.
See net.Server
for more information.
Stops the server from accepting new connections. This function is
asynchronous, the server is finally closed when the server emits a 'close'
event.
Set this property to reject connections when the server's connection count gets high.
The number of concurrent connections on the server.
File I/O is provided by simple wrappers around standard POSIX functions. To
use this module do require('fs')
. All the methods have asynchronous and
synchronous forms.
The asynchronous form always take a completion callback as its last argument.
The arguments passed to the completion callback depend on the method, but the
first argument is always reserved for an exception. If the operation was
completed successfully, then the first argument will be null
or undefined
.
Here is an example of the asynchronous version:
var fs = require('fs');
fs.unlink('/tmp/hello', function (err) {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
Here is the synchronous version:
var fs = require('fs');
fs.unlinkSync('/tmp/hello')
console.log('successfully deleted /tmp/hello');
With the asynchronous methods there is no guaranteed ordering. So the following is prone to error:
fs.rename('/tmp/hello', '/tmp/world', function (err) {
if (err) throw err;
console.log('renamed complete');
});
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
});
It could be that fs.stat
is executed before fs.rename
.
The correct way to do this is to chain the callbacks.
fs.rename('/tmp/hello', '/tmp/world', function (err) {
if (err) throw err;
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
});
});
In busy processes, the programmer is strongly encouraged to use the asynchronous versions of these calls. The synchronous versions will block the entire process until they complete--halting all connections.
Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.
Synchronous rename(2).
Asynchronous ftruncate(2). No arguments other than a possible exception are given to the completion callback.
Synchronous ftruncate(2).
Asynchronous chmod(2). No arguments other than a possible exception are given to the completion callback.
Synchronous chmod(2).
Asynchronous stat(2). The callback gets two arguments (err, stats)
where
stats
is a fs.Stats
object. It looks like this:
{ dev: 2049,
ino: 305352,
mode: 16877,
nlink: 12,
uid: 1000,
gid: 1000,
rdev: 0,
size: 4096,
blksize: 4096,
blocks: 8,
atime: '2009-06-29T11:11:55Z',
mtime: '2009-06-29T11:11:40Z',
ctime: '2009-06-29T11:11:40Z' }
See the fs.Stats
section below for more information.
Asynchronous lstat(2). The callback gets two arguments (err, stats)
where
stats
is a fs.Stats
object. lstat() is identical to stat(), except that if
path is a symbolic link, then the link itself is stat-ed, not the file that it
refers to.
Asynchronous fstat(2). The callback gets two arguments (err, stats)
where
stats
is a fs.Stats
object.
Synchronous stat(2). Returns an instance of fs.Stats
.
Synchronous lstat(2). Returns an instance of fs.Stats
.
Synchronous fstat(2). Returns an instance of fs.Stats
.
Asynchronous link(2). No arguments other than a possible exception are given to the completion callback.
Synchronous link(2).
Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback.
Synchronous symlink(2).
Asynchronous readlink(2). The callback gets two arguments (err,
resolvedPath)
.
Synchronous readlink(2). Returns the resolved path.
Asynchronous realpath(2). The callback gets two arguments (err,
resolvedPath)
.
Synchronous realpath(2). Returns the resolved path.
Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback.
Synchronous unlink(2).
Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.
Synchronous rmdir(2).
Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback.
Synchronous mkdir(2).
Asynchronous readdir(3). Reads the contents of a directory.
The callback gets two arguments (err, files)
where files
is an array of
the names of the files in the directory excluding '.'
and '..'
.
Synchronous readdir(3). Returns an array of filenames excluding '.'
and
'..'
.
Asynchronous close(2). No arguments other than a possible exception are given to the completion callback.
Synchronous close(2).
Asynchronous file open. See open(2). Flags can be 'r', 'r+', 'w', 'w+', 'a',
or 'a+'. mode
defaults to 0666. The callback gets two arguments (err, fd)
.
Synchronous open(2).
Write buffer
to the file specified by fd
.
offset
and length
determine the part of the buffer to be written.
position
refers to the offset from the beginning of the file where this data
should be written. If position
is null
, the data will be written at the
current position.
See pwrite(2).
The callback will be given two arguments (err, written)
where written
specifies how many bytes were written.
Note that it is unsafe to use fs.write
multiple times on the same file
without waiting for the callback. For this scenario,
fs.createWriteStream
is strongly recommended.
Synchronous version of buffer-based fs.write()
. Returns the number of bytes
written.
Synchronous version of string-based fs.write()
. Returns the number of bytes
written.
Read data from the file specified by fd
.
buffer
is the buffer that the data will be written to.
offset
is offset within the buffer where writing will start.
length
is an integer specifying the number of bytes to read.
position
is an integer specifying where to begin reading from in the file.
If position
is null
, data will be read from the current file position.
The callback is given the two arguments, (err, bytesRead)
.
Synchronous version of buffer-based fs.read
. Returns the number of
bytesRead
.
Synchronous version of string-based fs.read
. Returns the number of
bytesRead
.
Asynchronously reads the entire contents of a file. Example:
fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
console.log(data);
});
The callback is passed two arguments (err, data)
, where data
is the
contents of the file.
If no encoding is specified, then the raw buffer is returned.
Synchronous version of fs.readFile
. Returns the contents of the filename
.
If encoding
is specified then this function returns a string. Otherwise it
returns a buffer.
Asynchronously writes data to a file, replacing the file if it already exists.
data
can be a string or a buffer.
Example:
fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
The synchronous version of fs.writeFile
.
Watch for changes on filename
. The callback listener
will be called each
time the file is accessed.
The second argument is optional. The options
if provided should be an object
containing two members a boolean, persistent
, and interval
, a polling
value in milliseconds. The default is { persistent: true, interval: 0 }
.
The listener
gets two arguments the current stat object and the previous
stat object:
fs.watchFile(f, function (curr, prev) {
console.log('the current mtime is: ' + curr.mtime);
console.log('the previous mtime was: ' + prev.mtime);
});
These stat objects are instances of fs.Stat
.
If you want to be notified when the file was modified, not just accessed
you need to compare curr.mtime
and `prev.mtime.
Stop watching for changes on filename
.
Objects returned from fs.stat()
and fs.lstat()
are of this type.
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink()
(only valid with fs.lstat()
)stats.isFIFO()
stats.isSocket()
ReadStream
is a Readable Stream
.
Returns a new ReadStream object (See Readable Stream
).
options
is an object with the following defaults:
{ flags: 'r',
encoding: null,
fd: null,
mode: 0666,
bufferSize: 64 * 1024
}
options
can include start
and end
values to read a range of bytes from
the file instead of the entire file. Both start
and end
are inclusive and
start at 0. When used, both the limits must be specified always.
An example to read the last 10 bytes of a file which is 100 bytes long:
fs.createReadStream('sample.txt', {start: 90, end: 99});
WriteStream
is a Writable Stream
.
function (fd) { }
fd
is the file descriptor used by the WriteStream.
Returns a new WriteStream object (See Writable Stream
).
options
is an object with the following defaults:
This module contains utilities for dealing with file paths. Use
require('path')
to use it. It provides the following methods:
Normalize a string path, taking care of '..'
and '.'
parts.
When multiple slashes are found, they're replaces by a single one; when the path contains a trailing slash, it is preserved. On windows backslashes are used.
Example:
path.normalize('/foo/bar//baz/asdf/quux/..')
// returns
'/foo/bar/baz/asdf'
Join all arguments together and normalize the resulting path.
Example:
node> require('path').join(
... '/foo', 'bar', 'baz/asdf', 'quux', '..')
'/foo/bar/baz/asdf'
Resolves to
to an absolute path.
If to
isn't already absolute from
arguments are prepended in right to left
order, until an absolute path is found. If after using all from
paths still
no absolute path is found, the current working directory is used as well. The
resulting path is normalized, and trailing slashes are removed unless the path
gets resolved to the root directory.
Another way to think of it is as a sequence of cd
commands in a shell.
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
Is similar to:
cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd
The difference is that the different paths don't need to exist and may also be files.
Examples:
path.resolve('/foo/bar', './baz')
// returns
'/foo/bar/baz'
path.resolve('/foo/bar', '/tmp/file/')
// returns
'/tmp/file'
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// if currently in /home/myself/node, it returns
'/home/myself/node/wwwroot/static_files/gif/image.gif'
Return the directory name of a path. Similar to the Unix dirname
command.
Example:
path.dirname('/foo/bar/baz/asdf/quux')
// returns
'/foo/bar/baz/asdf'
Return the last portion of a path. Similar to the Unix basename
command.
Example:
path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'
path.basename('/foo/bar/baz/asdf/quux.html', '.html')
// returns
'quux'
Return the extension of the path. Everything after the last '.' in the last portion of the path. If there is no '.' in the last portion of the path or the only '.' is the first character, then it returns an empty string. Examples:
path.extname('index.html')
// returns
'.html'
path.extname('index')
// returns
''
Test whether or not the given path exists. Then, call the callback
argument
with either true or false. Example:
path.exists('/etc/passwd', function (exists) {
util.debug(exists ? "it's there" : "no passwd!");
});
Synchronous version of path.exists
.
The net
module provides you with an asynchronous network wrapper. It contains
methods for creating both servers and clients (called streams). You can include
this module with require("net");
Creates a new TCP server. The connectionListener
argument is
automatically set as a listener for the 'connection'
event.
options
is an object with the following defaults:
{ allowHalfOpen: false
}
If allowHalfOpen
is true
, then the socket won't automatically send FIN
packet when the other end of the socket sends a FIN packet. The socket becomes
non-readable, but still writable. You should call the end() method explicitly.
See 'end'
event for more information.
Construct a new socket object and opens a socket to the given location. When
the socket is established the 'connect'
event will be emitted.
The arguments for this method change the type of connection:
net.createConnection(port, [host])
Creates a TCP connection to port
on host
. If host
is omitted, localhost
will be assumed.
net.createConnection(path)
Creates unix socket connection to path
This class is used to create a TCP or UNIX server.
Here is an example of a echo server which listens for connections on port 8124:
var net = require('net');
var server = net.createServer(function (c) {
c.write('hello\r\n');
c.pipe(c);
});
server.listen(8124, 'localhost');
Test this by using telnet
:
telnet localhost 8124
To listen on the socket /tmp/echo.sock
the last line would just be
changed to
server.listen('/tmp/echo.sock');
Use nc
to connect to a UNIX domain socket server:
nc -U /tmp/echo.sock
net.Server
is an EventEmitter
with the following events:
Begin accepting connections on the specified port
and host
. If the
host
is omitted, the server will accept connections directed to any
IPv4 address (INADDR_ANY
).
This function is asynchronous. The last parameter callback
will be called
when the server has been bound.
One issue some users run into is getting EADDRINUSE
errors. Meaning
another server is already running on the requested port. One way of handling this
would be to wait a second and the try again. This can be done with
server.on('error', function (e) {
if (e.code == 'EADDRINUSE') {
console.log('Address in use, retrying...');
setTimeout(function () {
server.close();
server.listen(PORT, HOST);
}, 1000);
}
});
(Note: All sockets in Node are set SO_REUSEADDR already)
Start a UNIX socket server listening for connections on the given path
.
This function is asynchronous. The last parameter callback
will be called
when the server has been bound.
Start a server listening for connections on the given file descriptor.
This file descriptor must have already had the bind(2)
and listen(2)
system
calls invoked on it.
Stops the server from accepting new connections. This function is
asynchronous, the server is finally closed when the server emits a 'close'
event.
Returns the bound address of the server as seen by the operating system. Useful to find which port was assigned when giving getting an OS-assigned address
Example:
var server = net.createServer(function (socket) {
socket.end("goodbye\n");
});
// grab a random port.
server.listen(function() {
address = server.address();
console.log("opened server on %j", address);
});
Set this property to reject connections when the server's connection count gets high.
The number of concurrent connections on the server.
function (socket) {}
Emitted when a new connection is made. socket
is an instance of
net.Socket
.
function () {}
Emitted when the server closes.
This object is an abstraction of of a TCP or UNIX socket. net.Socket
instances implement a duplex Stream interface. They can be created by the
user and used as a client (with connect()
) or they can be created by Node
and passed to the user through the 'connection'
event of a server.
net.Socket
instances are EventEmitters with the following events:
Construct a new socket object.
options
is an object with the following defaults:
{ fd: null
type: null
allowHalfOpen: false
}
fd
allows you to specify the existing file descriptor of socket. type
specified underlying protocol. It can be 'tcp4'
, 'tcp6'
, or 'unix'
.
About allowHalfOpen
, refer to createServer()
and 'end'
event.
Opens the connection for a given socket. If port
and host
are given,
then the socket will be opened as a TCP socket, if host
is omitted,
localhost
will be assumed. If a path
is given, the socket will be
opened as a unix socket to that path.
Normally this method is not needed, as net.createConnection
opens the
socket. Use this only if you are implementing a custom Socket or if a
Socket is closed and you want to reuse it to connect to another server.
This function is asynchronous. When the 'connect'
event is emitted the
socket is established. If there is a problem connecting, the 'connect'
event will not be emitted, the 'error'
event will be emitted with
the exception.
The callback
parameter will be added as an listener for the 'connect'
event.
net.Socket
has the property that socket.write()
always works. This is to
help users get up an running quickly. The computer cannot necessarily keep up
with the amount of data that is written to a socket - the network connection simply
might be too slow. Node will internally queue up the data written to a socket and
send it out over the wire when it is possible. (Internally it is polling on
the socket's file descriptor for being writable).
The consequence of this internal buffering is that memory may grow. This property shows the number of characters currently buffered to be written. (Number of characters is approximately equal to the number of bytes to be written, but the buffer may contain strings, and the strings are lazily encoded, so the exact number of bytes is not known.)
Users who experience large or growing bufferSize
should attempt to
"throttle" the data flows in their program with pause()
and resume()`.
Sets the encoding (either 'ascii'
, 'utf8'
, or 'base64'
) for data that is
received.
This function has been removed in v0.3. It used to upgrade the connection to SSL/TLS. See the TLS for the new API.
Sends data on the socket. The second parameter specifies the encoding in the case of a string--it defaults to UTF8 encoding.
Returns true
if the entire data was flushed successfully to the kernel
buffer. Returns false
if all or part of the data was queued in user memory.
'drain'
will be emitted when the buffer is again free.
The optional callback
parameter will be executed when the data is finally
written out - this may not be immediately.
For UNIX sockets, it is possible to send a file descriptor through the
socket. Simply add the fileDescriptor
argument and listen for the 'fd'
event on the other end.
Half-closes the socket. I.E., it sends a FIN packet. It is possible the server will still send some data.
If data
is specified, it is equivalent to calling socket.write(data, encoding)
followed by socket.end()
.
Ensures that no more I/O activity happens on this socket. Only necessary in case of errors (parse error or so).
Pauses the reading of data. That is, 'data'
events will not be emitted.
Useful to throttle back an upload.
Resumes reading after a call to pause()
.
Sets the socket to timeout after timeout
milliseconds of inactivity on
the socket. By default net.Socket
do not have a timeout.
When an idle timeout is triggered the socket will receive a 'timeout'
event but the connection will not be severed. The user must manually end()
or destroy()
the socket.
If timeout
is 0, then the existing idle timeout is disabled.
The optional callback
parameter will be added as a one time listener for the 'timeout'
event.
Disables the Nagle algorithm. By default TCP connections use the Nagle
algorithm, they buffer data before sending it off. Setting noDelay
will
immediately fire off data each time socket.write()
is called.
Enable/disable keep-alive functionality, and optionally set the initial
delay before the first keepalive probe is sent on an idle socket.
Set initialDelay
(in milliseconds) to set the delay between the last
data packet received and the first keepalive probe. Setting 0 for
initialDelay will leave the value unchanged from the default
(or previous) setting.
The string representation of the remote IP address. For example,
'74.125.127.100'
or '2001:4860:a005::68'
.
This member is only present in server-side connections.
function () { }
Emitted when a socket connection successfully is established.
See connect()
.
function (data) { }
Emitted when data is received. The argument data
will be a Buffer
or
String
. Encoding of data is set by socket.setEncoding()
.
(See the section on Readable Socket
for more information.)
function () { }
Emitted when the other end of the socket sends a FIN packet.
By default (allowHalfOpen == false
) the socket will destroy its file
descriptor once it has written out its pending write queue. However, by
setting allowHalfOpen == true
the socket will not automatically end()
its side allowing the user to write arbitrary amounts of data, with the
caveat that the user is required to end()
their side now.
function () { }
Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection.
See also: socket.setTimeout()
function () { }
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
function (exception) { }
Emitted when an error occurs. The 'close'
event will be called directly
following this event.
function (had_error) { }
Emitted once the socket is fully closed. The argument had_error
is a boolean
which says if the socket was closed due to a transmission error.
Tests if input is an IP address. Returns 0 for invalid strings, returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.
Returns true if input is a version 4 IP address, otherwise returns false.
Returns true if input is a version 6 IP address, otherwise returns false.
Datagram sockets are available through require('dgram')
. Datagrams are most commonly
handled as IP/UDP messages but they can also be used over Unix domain sockets.
function (msg, rinfo) { }
Emitted when a new datagram is available on a socket. msg
is a Buffer
and rinfo
is
an object with the sender's address information and the number of bytes in the datagram.
function () { }
Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets
are created. Unix domain sockets do not start listening until calling bind()
on them.
function () { }
Emitted when a socket is closed with close()
. No new message
events will be emitted
on this socket.
Creates a datagram socket of the specified types. Valid types are:
udp4
, udp6
, and unix_dgram
.
Takes an optional callback which is added as a listener for message
events.
For Unix domain datagram sockets, the destination address is a pathname in the filesystem.
An optional callback may be supplied that is invoked after the sendto
call is completed
by the OS. It is not safe to re-use buf
until the callback is invoked. Note that
unless the socket is bound to a pathname with bind()
there is no way to receive messages
on this socket.
Example of sending a message to syslogd on OSX via Unix domain socket /var/run/syslog
:
var dgram = require('dgram');
var message = new Buffer("A message to log.");
var client = dgram.createSocket("unix_dgram");
client.send(message, 0, message.length, "/var/run/syslog",
function (err, bytes) {
if (err) {
throw err;
}
console.log("Wrote " + bytes + " bytes to socket.");
});
For UDP sockets, the destination port and IP address must be specified. A string
may be supplied for the address
parameter, and it will be resolved with DNS. An
optional callback may be specified to detect any DNS errors and when buf
may be
re-used. Note that DNS lookups will delay the time that a send takes place, at
least until the next tick. The only way to know for sure that a send has taken place
is to use the callback.
Example of sending a UDP packet to a random port on localhost
;
var dgram = require('dgram');
var message = new Buffer("Some bytes");
var client = dgram.createSocket("udp4");
client.send(message, 0, message.length, 41234, "localhost");
client.close();
For Unix domain datagram sockets, start listening for incoming datagrams on a
socket specified by path
. Note that clients may send()
without bind()
,
but no datagrams will be received without a bind()
.
Example of a Unix domain datagram server that echoes back all messages it receives:
var dgram = require("dgram");
var serverPath = "/tmp/dgram_server_sock";
var server = dgram.createSocket("unix_dgram");
server.on("message", function (msg, rinfo) {
console.log("got: " + msg + " from " + rinfo.address);
server.send(msg, 0, msg.length, rinfo.address);
});
server.on("listening", function () {
console.log("server listening " + server.address().address);
})
server.bind(serverPath);
Example of a Unix domain datagram client that talks to this server:
var dgram = require("dgram");
var serverPath = "/tmp/dgram_server_sock";
var clientPath = "/tmp/dgram_client_sock";
var message = new Buffer("A message at " + (new Date()));
var client = dgram.createSocket("unix_dgram");
client.on("message", function (msg, rinfo) {
console.log("got: " + msg + " from " + rinfo.address);
});
client.on("listening", function () {
console.log("client listening " + client.address().address);
client.send(message, 0, message.length, serverPath);
});
client.bind(clientPath);
For UDP sockets, listen for datagrams on a named port
and optional address
. If
address
is not specified, the OS will try to listen on all addresses.
Example of a UDP server listening on port 41234:
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
var messageToSend = new Buffer("A message to send");
server.on("message", function (msg, rinfo) {
console.log("server got: " + msg + " from " +
rinfo.address + ":" + rinfo.port);
});
server.on("listening", function () {
var address = server.address();
console.log("server listening " +
address.address + ":" + address.port);
});
server.bind(41234);
// server listening 0.0.0.0:41234
Close the underlying socket and stop listening for data on it. UDP sockets
automatically listen for messages, even if they did not call bind()
.
Returns an object containing the address information for a socket. For UDP sockets,
this object will contain address
and port
. For Unix domain sockets, it will contain
only address
.
Sets or clears the SO_BROADCAST
socket option. When this option is set, UDP packets
may be sent to a local interface's broadcast address.
Sets the IP_TTL
socket option. TTL stands for "Time to Live," but in this context it
specifies the number of IP hops that a packet is allowed to go through. Each router or
gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a
router, it will not be forwarded. Changing TTL values is typically done for network
probes or when multicasting.
The argument to setTTL()
is a number of hops between 1 and 255. The default on most
systems is 64.
Sets the IP_MULTICAST_TTL
socket option. TTL stands for "Time to Live," but in this
context it specifies the number of IP hops that a packet is allowed to go through,
specifically for multicast traffic. Each router or gateway that forwards a packet
decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
The argument to setMulticastTTL()
is a number of hops between 0 and 255. The default on most
systems is 64.
Sets or clears the IP_MULTICAST_LOOP
socket option. When this option is set, multicast
packets will also be received on the local interface.
Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP
socket option.
If multicastAddress
is not specified, the OS will try to add membership to all valid
interfaces.
Opposite of addMembership
- tells the kernel to leave a multicast group with
IP_DROP_MEMBERSHIP
socket option. This is automatically called by the kernel
when the socket is closed or process terminates, so most apps will never need to call
this.
If multicastAddress
is not specified, the OS will try to drop membership to all valid
interfaces.
Use require('dns')
to access this module.
Here is an example which resolves 'www.google.com'
then reverse
resolves the IP addresses which are returned.
var dns = require('dns');
dns.resolve4('www.google.com', function (err, addresses) {
if (err) throw err;
console.log('addresses: ' + JSON.stringify(addresses));
addresses.forEach(function (a) {
dns.reverse(a, function (err, domains) {
if (err) {
console.log('reverse for ' + a + ' failed: ' +
err.message);
} else {
console.log('reverse for ' + a + ': ' +
JSON.stringify(domains));
}
});
});
});
Resolves a domain (e.g. 'google.com'
) into the first found A (IPv4) or
AAAA (IPv6) record.
The callback has arguments (err, address, family)
. The address
argument
is a string representation of a IP v4 or v6 address. The family
argument
is either the integer 4 or 6 and denotes the family of address
(not
necessarily the value initially passed to lookup
).
Resolves a domain (e.g. 'google.com'
) into an array of the record types
specified by rrtype. Valid rrtypes are A
(IPV4 addresses), AAAA
(IPV6
addresses), MX
(mail exchange records), TXT
(text records), SRV
(SRV
records), and PTR
(used for reverse IP lookups).
The callback has arguments (err, addresses)
. The type of each item
in addresses
is determined by the record type, and described in the
documentation for the corresponding lookup methods below.
On error, err
would be an instanceof Error
object, where err.errno
is
one of the error codes listed below and err.message
is a string describing
the error in English.
The same as dns.resolve()
, but only for IPv4 queries (A
records).
addresses
is an array of IPv4 addresses (e.g.
['74.125.79.104', '74.125.79.105', '74.125.79.106']
).
The same as dns.resolve4()
except for IPv6 queries (an AAAA
query).
The same as dns.resolve()
, but only for mail exchange queries (MX
records).
addresses
is an array of MX records, each with a priority and an exchange
attribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]
).
The same as dns.resolve()
, but only for text queries (TXT
records).
addresses
is an array of the text records available for domain
(e.g.,
['v=spf1 ip4:0.0.0.0 ~all']
).
The same as dns.resolve()
, but only for service records (SRV
records).
addresses
is an array of the SRV records available for domain
. Properties
of SRV records are priority, weight, port, and name (e.g.,
[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]
).
Reverse resolves an ip address to an array of domain names.
The callback has arguments (err, domains)
.
If there an an error, err
will be non-null and an instanceof the Error
object.
Each DNS query can return an error code.
To use the HTTP server and client one must require('http')
.
The HTTP interfaces in Node are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses--the user is able to stream data.
HTTP message headers are represented by an object like this:
{ 'content-length': '123',
'content-type': 'text/plain',
'connection': 'keep-alive',
'accept': '*/*' }
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, Node's HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.
This is an EventEmitter
with the following events:
function (request, response) { }
request
is an instance of http.ServerRequest
and response
is
an instance of http.ServerResponse
function (stream) { }
When a new TCP stream is established. stream
is an object of type
net.Stream
. Usually users will not want to access this event. The
stream
can also be accessed at request.connection
.
function (errno) { }
Emitted when the server closes.
function (request, response) {}
Emitted each time there is request. Note that there may be multiple requests per connection (in the case of keep-alive connections).
function (request, response) {}
Emitted each time a request with an http Expect: 100-continue is received. If this event isn't listened for, the server will automatically respond with a 100 Continue as appropriate.
Handling this event involves calling response.writeContinue
if the client
should continue to send the request body, or generating an appropriate HTTP
response (e.g., 400 Bad Request) if the client should not continue to send the
request body.
Note that when this event is emitted and handled, the request
event will
not be emitted.
function (request, socket, head)
Emitted each time a client requests a http upgrade. If this event isn't listened for, then clients requesting an upgrade will have their connections closed.
request
is the arguments for the http request, as it is in the request event.socket
is the network socket between the server and client.head
is an instance of Buffer, the first packet of the upgraded stream, this may be empty.After this event is emitted, the request's socket will not have a data
event listener, meaning you will need to bind to it in order to handle data
sent to the server on that socket.
function (exception) {}
If a client connection emits an 'error' event - it will forwarded here.
Returns a new web server object.
The requestListener
is a function which is automatically
added to the 'request'
event.
Begin accepting connections on the specified port and hostname. If the
hostname is omitted, the server will accept connections directed to any
IPv4 address (INADDR_ANY
).
To listen to a unix socket, supply a filename instead of port and hostname.
This function is asynchronous. The last parameter callback
will be called
when the server has been bound to the port.
Start a UNIX socket server listening for connections on the given path
.
This function is asynchronous. The last parameter callback
will be called
when the server has been bound.
Stops the server from accepting new connections.
This object is created internally by a HTTP server -- not by
the user -- and passed as the first argument to a 'request'
listener.
This is an EventEmitter
with the following events:
function (chunk) { }
Emitted when a piece of the message body is received.
Example: A chunk of the body is given as the single
argument. The transfer-encoding has been decoded. The
body chunk is a string. The body encoding is set with
request.setBodyEncoding()
.
function () { }
Emitted exactly once for each message. No arguments. After emitted no other events will be emitted on the request.
The request method as a string. Read only. Example:
'GET'
, 'DELETE'
.
Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:
GET /status?name=ryan HTTP/1.1\r\n
Accept: text/plain\r\n
\r\n
Then request.url
will be:
'/status?name=ryan'
If you would like to parse the URL into its parts, you can use
require('url').parse(request.url)
. Example:
node> require('url').parse('/status?name=ryan')
{ href: '/status?name=ryan',
search: '?name=ryan',
query: 'name=ryan',
pathname: '/status' }
If you would like to extract the params from the query string,
you can use the require('querystring').parse
function, or pass
true
as the second argument to require('url').parse
. Example:
node> require('url').parse('/status?name=ryan', true)
{ href: '/status?name=ryan',
search: '?name=ryan',
query: { name: 'ryan' },
pathname: '/status' }
Read only.
Read only; HTTP trailers (if present). Only populated after the 'end' event.
The HTTP protocol version as a string. Read only. Examples:
'1.1'
, '1.0'
.
Also request.httpVersionMajor
is the first integer and
request.httpVersionMinor
is the second.
Set the encoding for the request body. Either 'utf8'
or 'binary'
. Defaults
to null
, which means that the 'data'
event will emit a Buffer
object..
Pauses request from emitting events. Useful to throttle back an upload.
Resumes a paused request.
The net.Stream
object associated with the connection.
With HTTPS support, use request.connection.verifyPeer() and request.connection.getPeerCertificate() to obtain the client's authentication details.
This object is created internally by a HTTP server--not by the user. It is
passed as the second parameter to the 'request'
event. It is a Writable Stream
.
Sends a HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the the checkContinue
event on
Server
.
Sends a response header to the request. The status code is a 3-digit HTTP
status code, like 404
. The last argument, headers
, are the response headers.
Optionally one can give a human-readable reasonPhrase
as the second
argument.
Example:
var body = 'hello world';
response.writeHead(200, {
'Content-Length': body.length,
'Content-Type': 'text/plain' });
This method must only be called once on a message and it must
be called before response.end()
is called.
If you call response.write()
or response.end()
before calling this, the
implicit/mutable headers will be calculated and call this function for you.
When using implicit headers (not calling response.writeHead()
explicitly), this property
controls the status code that will be send to the client when the headers get
flushed.
Example:
response.statusCode = 404;
Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, it's value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.
Example:
response.setHeader("Content-Type", "text/html");
or
response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive. This can only be called before headers get implicitly flushed.
Example:
var contentType = response.getHeader('content-type');
Removes a header that's queued for implicit sending.
Example:
response.removeHeader("Content-Encoding");
If this method is called and response.writeHead()
has not been called, it will
switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.
chunk
can be a string or a buffer. If chunk
is a string,
the second parameter specifies how to encode it into a byte stream.
By default the encoding
is 'utf8'
.
Note: This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.
The first time response.write()
is called, it will send the buffered
header information and the first body to the client. The second time
response.write()
is called, Node assumes you're going to be streaming
data, and sends that separately. That is, the response is buffered up to the
first chunk of body.
This method adds HTTP trailing headers (a header but at the end of the message) to the response.
Trailers will only be emitted if chunked encoding is used for the response; if it is not (e.g., if the request was HTTP/1.0), they will be silently discarded.
Note that HTTP requires the Trailer
header to be sent if you intend to
emit trailers, with a list of the header fields in its value. E.g.,
response.writeHead(200, { 'Content-Type': 'text/plain',
'Trailer': 'TraceInfo' });
response.write(fileData);
response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
response.end();
This method signals to the server that all of the response headers and body
has been sent; that server should consider this message complete.
The method, response.end()
, MUST be called on each
response.
If data
is specified, it is equivalent to calling response.write(data, encoding)
followed by response.end()
.
Node maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.
Options:
host
: A domain name or IP address of the server to issue the request to.port
: Port of remote server.method
: A string specifying the HTTP request method. Possible values:
'GET'
(default), 'POST'
, 'PUT'
, and 'DELETE'
.path
: Request path. Should include query string and fragments if any.
E.G. '/index.html?page=12'
headers
: An object containing request headers.http.request()
returns an instance of the http.ClientRequest
class. The ClientRequest
instance is a writable stream. If one needs to
upload a file with a POST request, then write to the ClientRequest
object.
Example:
var options = {
host: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
Note that in the example req.end()
was called. With http.request()
one
must always call req.end()
to signify that you're done with the request -
even if there is no data being written to the request body.
If any error is encountered during the request (be that with DNS resolution,
TCP level errors, or actual HTTP parse errors) an 'error'
event is emitted
on the returned request object.
There are a few special headers that should be noted.
Sending a 'Connection: keep-alive' will notify Node that the connection to the server should be persisted until the next request.
Sending a 'Content-length' header will disable the default chunked encoding.
Sending an 'Expect' header will immediately send the request headers.
Usually, when sending 'Expect: 100-continue', you should both set a timeout
and listen for the continue
event. See RFC2616 Section 8.2.3 for more
information.
Since most requests are GET requests without bodies, Node provides this
convenience method. The only difference between this method and http.request()
is
that it sets the method to GET and calls req.end()
automatically.
Example:
var options = {
host: 'www.google.com',
port: 80,
path: '/index.html'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
http.request()
uses a special Agent
for managing multiple connections to
an HTTP server. Normally Agent
instances should not be exposed to user
code, however in certain situations it's useful to check the status of the
agent. The http.getAgent()
function allows you to access the agents.
function (request, socket, head)
Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.
See the description of the upgrade
event for http.Server
for further details.
function ()
Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.
By default set to 5. Determines how many concurrent sockets the agent can have open.
An array of sockets currently in use by the Agent. Do not modify.
A queue of requests waiting to be sent to sockets.
This object is created internally and returned from http.request()
. It
represents an in-progress request whose header has already been queued. The
header is still mutable using the setHeader(name, value)
, getHeader(name)
,
removeHeader(name)
API. The actual header will be sent along with the first
data chunk or when closing the connection.
To get the response, add a listener for 'response'
to the request object.
'response'
will be emitted from the request object when the response
headers have been received. The 'response'
event is executed with one
argument which is an instance of http.ClientResponse
.
During the 'response'
event, one can add listeners to the
response object; particularly to listen for the 'data'
event. Note that
the 'response'
event is called before any part of the response body is received,
so there is no need to worry about racing to catch the first part of the
body. As long as a listener for 'data'
is added during the 'response'
event, the entire body will be caught.
// Good
request.on('response', function (response) {
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
// Bad - misses all or part of the body
request.on('response', function (response) {
setTimeout(function () {
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
}, 10);
});
This is a Writable Stream
.
This is an EventEmitter
with the following events:
function (response) { }
Emitted when a response is received to this request. This event is emitted only once. The
response
argument will be an instance of http.ClientResponse
.
Sends a chunk of the body. By calling this method
many times, the user can stream a request body to a
server--in that case it is suggested to use the
['Transfer-Encoding', 'chunked']
header line when
creating the request.
The chunk
argument should be an array of integers
or a string.
The encoding
argument is optional and only
applies when chunk
is a string.
Finishes sending the request. If any parts of the body are
unsent, it will flush them to the stream. If the request is
chunked, this will send the terminating '0\r\n\r\n'
.
If data
is specified, it is equivalent to calling request.write(data, encoding)
followed by request.end()
.
Aborts a request. (New since v0.3.8.)
This object is created when making a request with http.request()
. It is
passed to the 'response'
event of the request object.
The response implements the Readable Stream
interface.
function (chunk) {}
Emitted when a piece of the message body is received.
function () {}
Emitted exactly once for each message. No arguments. After emitted no other events will be emitted on the response.
The 3-digit HTTP response status code. E.G. 404
.
The HTTP version of the connected-to server. Probably either
'1.1'
or '1.0'
.
Also response.httpVersionMajor
is the first integer and
response.httpVersionMinor
is the second.
The response headers object.
The response trailers object. Only populated after the 'end' event.
Set the encoding for the response body. Either 'utf8'
, 'ascii'
, or 'base64'
.
Defaults to null
, which means that the 'data'
event will emit a Buffer
object..
Pauses response from emitting events. Useful to throttle back a download.
Resumes a paused response.
HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a separate module.
Example:
// curl -k https://localhost:8000/
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
Makes a request to a secure web server.
Similar options to http.request()
.
Example:
var https = require('https');
var options = {
host: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET'
};
var req = https.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
The options argument has the following options
'localhost'
.'/'
.'GET'
.null
.null
.Like http.get()
but for HTTPS.
Example:
This module has utilities for URL resolution and parsing.
Call require('url')
to use it.
Parsed URL objects have some or all of the following fields, depending on whether or not they exist in the URL string. Any parts that are not in the URL string will not be in the parsed object. Examples are shown for the URL
'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
href
: The full URL that was originally parsed.
Example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
protocol
: The request protocol.
Example: 'http:'
host
: The full host portion of the URL, including port and authentication information.
Example: 'user:pass@host.com:8080'
auth
: The authentication information portion of a URL.
Example: 'user:pass'
hostname
: Just the hostname portion of the host.
Example: 'host.com'
port
: The port number portion of the host.
Example: '8080'
pathname
: The path section of the URL, that comes after the host and before the query, including the initial slash if present.
Example: '/p/a/t/h'
search
: The 'query string' portion of the URL, including the leading question mark.
Example: '?query=string'
query
: Either the 'params' portion of the query string, or a querystring-parsed object.
Example: 'query=string'
or {'query':'string'}
hash
: The 'fragment' portion of the URL including the pound-sign.
Example: '#hash'
The following methods are provided by the URL module:
Take a URL string, and return an object. Pass true
as the second argument to also parse
the query string using the querystring
module.
Take a parsed URL object, and return a formatted URL string.
Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.
This module provides utilities for dealing with query strings. It provides the following methods:
Serialize an object to a query string. Optionally override the default separator and assignment characters.
Example:
querystring.stringify({foo: 'bar'})
// returns
'foo=bar'
querystring.stringify({foo: 'bar', baz: 'bob'}, ';', ':')
// returns
'foo:bar;baz:bob'
Deserialize a query string to an object. Optionally override the default separator and assignment characters.
Example:
querystring.parse('a=b&b=c')
// returns
{ a: 'b', b: 'c' }
The escape function used by querystring.stringify
,
provided so that it could be overridden if necessary.
The unescape function used by querystring.parse
,
provided so that it could be overridden if necessary.
A Read-Eval-Print-Loop (REPL) is available both as a standalone program and easily includable in other programs. REPL provides a way to interactively run JavaScript and see the results. It can be used for debugging, testing, or just trying things out.
By executing node
without any arguments from the command-line you will be
dropped into the REPL. It has simplistic emacs line-editing.
mjr:~$ node
Type '.help' for options.
> a = [ 1, 2, 3];
[ 1, 2, 3 ]
> a.forEach(function (v) {
... console.log(v);
... });
1
2
3
For advanced line-editors, start node with the environmental variable NODE_NO_READLINE=1
.
This will start the REPL in canonical terminal settings which will allow you to use with rlwrap
.
For example, you could add this to your bashrc file:
alias node="env NODE_NO_READLINE=1 rlwrap node"
Starts a REPL with prompt
as the prompt and stream
for all I/O. prompt
is optional and defaults to >
. stream
is optional and defaults to
process.stdin
.
Multiple REPLs may be started against the same running instance of node. Each will share the same global object but will have unique I/O.
Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:
var net = require("net"),
repl = require("repl");
connections = 0;
repl.start("node via stdin> ");
net.createServer(function (socket) {
connections += 1;
repl.start("node via Unix socket> ", socket);
}).listen("/tmp/node-repl-sock");
net.createServer(function (socket) {
connections += 1;
repl.start("node via TCP socket> ", socket);
}).listen(5001);
Running this program from the command line will start a REPL on stdin. Other
REPL clients may connect through the Unix socket or TCP socket. telnet
is useful
for connecting to TCP sockets, and socat
can be used to connect to both Unix and
TCP sockets.
By starting a REPL from a Unix socket-based server instead of stdin, you can connect to a long-running node process without restarting it.
Inside the REPL, Control+D will exit. Multi-line expressions can be input.
The special variable _
(underscore) contains the result of the last expression.
> [ "a", "b", "c" ]
[ 'a', 'b', 'c' ]
> _.length
3
> _ += 1
4
The REPL provides access to any variables in the global scope. You can expose a variable
to the REPL explicitly by assigning it to the context
object associated with each
REPLServer
. For example:
// repl_test.js
var repl = require("repl"),
msg = "message";
repl.start().context.m = msg;
Things in the context
object appear as local within the REPL:
mjr:~$ node repl_test.js
> m
'message'
There are a few special REPL commands:
You can access this module with:
var vm = require('vm');
JavaScript code can be compiled and run immediately or compiled, saved, and run later.
vm.runInThisContext()
compiles code
as if it were loaded from filename
,
runs it and returns the result. Running code does not have access to local scope. filename
is optional.
Example of using vm.runInThisContext
and eval
to run the same code:
var localVar = 123,
usingscript, evaled,
vm = require('vm');
usingscript = vm.runInThisContext('localVar = 1;',
'myfile.vm');
console.log('localVar: ' + localVar + ', usingscript: ' +
usingscript);
evaled = eval('localVar = 1;');
console.log('localVar: ' + localVar + ', evaled: ' +
evaled);
// localVar: 123, usingscript: 1
// localVar: 1, evaled: 1
vm.runInThisContext
does not have access to the local scope, so localVar
is unchanged.
eval
does have access to the local scope, so localVar
is changed.
In case of syntax error in code
, vm.runInThisContext
emits the syntax error to stderr
and throws.an exception.
vm.runInNewContext
compiles code
to run in sandbox
as if it were loaded from filename
,
then runs it and returns the result. Running code does not have access to local scope and
the object sandbox
will be used as the global object for code
.
sandbox
and filename
are optional.
Example: compile and execute code that increments a global variable and sets a new one. These globals are contained in the sandbox.
var util = require('util'),
vm = require('vm'),
sandbox = {
animal: 'cat',
count: 2
};
vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');
console.log(util.inspect(sandbox));
// { animal: 'cat', count: 3, name: 'kitty' }
Note that running untrusted code is a tricky business requiring great care. To prevent accidental
global variable leakage, vm.runInNewContext
is quite useful, but safely running untrusted code
requires a separate process.
In case of syntax error in code
, vm.runInThisContext
emits the syntax error to stderr
and throws an exception.
createScript
compiles code
as if it were loaded from filename
,
but does not run it. Instead, it returns a vm.Script
object representing this compiled code.
This script can be run later many times using methods below.
The returned script is not bound to any global object.
It is bound before each run, just for that run. filename
is optional.
In case of syntax error in code
, createScript
prints the syntax error to stderr
and throws an exception.
Similar to vm.runInThisContext
but a method of a precompiled Script
object.
script.runInThisContext
runs the code of script
and returns the result.
Running code does not have access to local scope, but does have access to the global
object
(v8: in actual context).
Example of using script.runInThisContext
to compile code once and run it multiple times:
var vm = require('vm');
globalVar = 0;
var script = vm.createScript('globalVar += 1', 'myfile.vm');
for (var i = 0; i < 1000 ; i += 1) {
script.runInThisContext();
}
console.log(globalVar);
// 1000
Similar to vm.runInNewContext
a method of a precompiled Script
object.
script.runInNewContext
runs the code of script
with sandbox
as the global object and returns the result.
Running code does not have access to local scope. sandbox
is optional.
Example: compile code that increments a global variable and sets one, then execute this code multiple times. These globals are contained in the sandbox.
var util = require('util'),
vm = require('vm'),
sandbox = {
animal: 'cat',
count: 2
};
var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');
for (var i = 0; i < 10 ; i += 1) {
script.runInNewContext(sandbox);
}
console.log(util.inspect(sandbox));
// { animal: 'cat', count: 12, name: 'kitty' }
Note that running untrusted code is a tricky business requiring great care. To prevent accidental
global variable leakage, script.runInNewContext
is quite useful, but safely running untrusted code
requires a separate process.
Node provides a tri-directional popen(3)
facility through the ChildProcess
class.
It is possible to stream data through the child's stdin
, stdout
, and
stderr
in a fully non-blocking way.
To create a child process use require('child_process').spawn()
.
Child processes always have three streams associated with them. child.stdin
,
child.stdout
, and child.stderr
.
ChildProcess
is an EventEmitter
.
function (code, signal) {}
This event is emitted after the child process ends. If the process terminated
normally, code
is the final exit code of the process, otherwise null
. If
the process terminated due to receipt of a signal, signal
is the string name
of the signal, otherwise null
.
See waitpid(2)
.
A Writable Stream
that represents the child process's stdin
.
Closing this stream via end()
often causes the child process to terminate.
A Readable Stream
that represents the child process's stdout
.
A Readable Stream
that represents the child process's stderr
.
The PID of the child process.
Example:
var spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
console.log('Spawned child pid: ' + grep.pid);
grep.stdin.end();
Launches a new process with the given command
, with command line arguments in args
.
If omitted, args
defaults to an empty Array.
The third argument is used to specify additional options, which defaults to:
{ cwd: undefined,
env: process.env,
customFds: [-1, -1, -1],
setsid: false
}
cwd
allows you to specify the working directory from which the process is spawned.
Use env
to specify environment variables that will be visible to the new process.
With customFds
it is possible to hook up the new process' [stdin, stout, stderr] to
existing streams; -1
means that a new stream should be created. setsid
,
if set true, will cause the subprocess to be run in a new session.
Example of running ls -lh /usr
, capturing stdout
, stderr
, and the exit code:
var util = require('util'),
spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('exit', function (code) {
console.log('child process exited with code ' + code);
});
Example: A very elaborate way to run 'ps ax | grep ssh'
var util = require('util'),
spawn = require('child_process').spawn,
ps = spawn('ps', ['ax']),
grep = spawn('grep', ['ssh']);
ps.stdout.on('data', function (data) {
grep.stdin.write(data);
});
ps.stderr.on('data', function (data) {
console.log('ps stderr: ' + data);
});
ps.on('exit', function (code) {
if (code !== 0) {
console.log('ps process exited with code ' + code);
}
grep.stdin.end();
});
grep.stdout.on('data', function (data) {
console.log(data);
});
grep.stderr.on('data', function (data) {
console.log('grep stderr: ' + data);
});
grep.on('exit', function (code) {
if (code !== 0) {
console.log('grep process exited with code ' + code);
}
});
Example of checking for failed exec:
var spawn = require('child_process').spawn,
child = spawn('bad_command');
child.stderr.setEncoding('utf8');
child.stderr.on('data', function (data) {
if (/^execvp\(\)/.test(data)) {
console.log('Failed to start child process.');
}
});
See also: child_process.exec()
High-level way to execute a command as a child process, buffer the output, and return it all in a callback.
var util = require('util'),
exec = require('child_process').exec,
child;
child = exec('cat *.js bad_file | wc -l',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
The callback gets the arguments (error, stdout, stderr)
. On success, error
will be null
. On error, error
will be an instance of Error
and err.code
will be the exit code of the child process, and err.signal
will be set to the
signal that terminated the process.
There is a second optional argument to specify several options. The default options are
{ encoding: 'utf8',
timeout: 0,
maxBuffer: 200*1024,
killSignal: 'SIGTERM',
cwd: null,
env: null }
If timeout
is greater than 0, then it will kill the child process
if it runs longer than timeout
milliseconds. The child process is killed with
killSignal
(default: 'SIGTERM'
). maxBuffer
specifies the largest
amount of data allowed on stdout or stderr - if this value is exceeded then
the child process is killed.
Send a signal to the child process. If no argument is given, the process will
be sent 'SIGTERM'
. See signal(7)
for a list of available signals.
var spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
grep.on('exit', function (code, signal) {
console.log('child process terminated due to receipt of signal '+signal);
});
// send SIGHUP to process
grep.kill('SIGHUP');
Note that while the function is called kill
, the signal delivered to the child
process may not actually kill it. kill
really just sends a signal to a process.
See kill(2)
This module is used for writing unit tests for your applications, you can
access it with require('assert')
.
Tests if actual
is equal to expected
using the operator provided.
Tests if value is a true
value, it is equivalent to assert.equal(true, value, message);
Tests shallow, coercive equality with the equal comparison operator ( ==
).
Tests shallow, coercive non-equality with the not equal comparison operator ( !=
).
Tests for deep equality.
Tests for any deep inequality.
Tests strict equality, as determined by the strict equality operator ( ===
)
Tests strict non-equality, as determined by the strict not equal operator ( !==
)
Expects block
to throw an error. error
can be constructor, regexp or
validation function.
Validate instanceof using constructor:
assert.throws(
function() {
throw new Error("Wrong value");
},
Error
);
Validate error message using RegExp:
assert.throws(
function() {
throw new Error("Wrong value");
},
/value/
);
Custom error validation:
assert.throws(
function() {
throw new Error("Wrong value");
},
function(err) {
if ( (err instanceof Error) && /value/.test(err) ) {
return true;
}
},
"unexpected error"
);
Expects block
not to throw an error, see assert.throws for details.
Tests if value is not a false value, throws if it is a true value. Useful when
testing the first argument, error
in callbacks.
Use require('tty')
to access this module.
Example:
var tty = require('tty');
tty.setRawMode(true);
process.stdin.resume();
process.stdin.on('keypress', function(char, key) {
if (key && key.ctrl && key.name == 'c') {
console.log('graceful exit');
process.exit()
}
});
Spawns a new process with the executable pointed to by path
as the session
leader to a new pseudo terminal.
Returns an array [slaveFD, childProcess]
. slaveFD
is the file descriptor
of the slave end of the pseudo terminal. childProcess
is a child process
object.
Returns true
or false
depending on if the fd
is associated with a
terminal.
mode
should be true
or false
. This sets the properties of the current
process's stdin fd to act either as a raw device or default.
ioctl
s the window size settings to the file descriptor.
Returns [row, col]
for the TTY associated with the file descriptor.
Use require('os')
to access this module.
Returns the hostname of the operating system.
Returns the operating system name.
Returns the operating system release.
Returns the system uptime in seconds.
Returns an array containing the 1, 5, and 15 minute load averages.
Returns the total amount of system memory in bytes.
Returns the amount of free system memory in bytes.
Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of CPU ticks spent in: user, nice, sys, idle, and irq).
Example inspection of os.cpus:
V8 comes with an extensive debugger which is accessible out-of-process via a
simple TCP protocol.
Node has a built-in client for this debugger. To use this, start Node with the
debug
argument; a prompt will appear:
% node debug myscript.js
debug>
At this point myscript.js
is not yet running. To start the script, enter
the command run
. If everything works okay, the output should look like
this:
% node debug myscript.js
debug> run
debugger listening on port 5858
connecting...ok
Node's debugger client doesn't support the full range of commands, but
simple step and inspection is possible. By putting the statement debugger;
into the source code of your script, you will enable a breakpoint.
For example, suppose myscript.js
looked like this:
// myscript.js
x = 5;
setTimeout(function () {
debugger;
console.log("world");
}, 1000);
console.log("hello");
Then once the debugger is run, it will break on line 4.
% ./node debug myscript.js
debug> run
debugger listening on port 5858
connecting...ok
hello
break in #<an Object>._onTimeout(), myscript.js:4
debugger;
^
debug> next
break in #<an Object>._onTimeout(), myscript.js:5
console.log("world");
^
debug> print x
5
debug> print 2+2
4
debug> next
world
break in #<an Object>._onTimeout() returning undefined, myscript.js:6
}, 1000);
^
debug> quit
A debugging session is active. Quit anyway? (y or n) y
%
The print
command allows you to evaluate variables. The next
command steps
over to the next line. There are a few other commands available and more to
come type help
to see others.
The V8 debugger can be enabled and accessed either by starting Node with
the --debug
command-line flag or by signaling an existing Node process
with SIGUSR1
.
There are many third party modules for Node. At the time of writing, August 2010, the master repository of modules is the wiki page.
This appendix is intended as a SMALL guide to new-comers to help them quickly find what are considered to be quality modules. It is not intended to be a complete list. There may be better more complete modules found elsewhere.
Module Installer: npm
HTTP Middleware: Connect
Web Framework: Express
Web Sockets: Socket.IO
HTML Parsing: HTML5
Serialization: msgpack
Scraping: Apricot
Debugger: ndb is a CLI debugger inspector is a web based tool.
Testing/TDD/BDD: vows, expresso, mjsunit.runner
Patches to this list are welcome.