Node.js Manual & Documentation
Table Of Contents
- Synopsis 概要
- Global Objects 全局對象
- Timers 定時器
- Modules 模塊
- Addenda: Package Manager Tips 附錄:包管理技巧
- Addons 擴展插件
- process 進程
- util 工具模塊
- Events 事件模塊
- Buffers 緩沖器
- new Buffer(size)
- new Buffer(array)
- new Buffer(str, encoding='utf8')
- buffer.write(string, offset=0, encoding='utf8')
- buffer.toString(encoding, start=0, end=buffer.length)
- buffer[index]
- Buffer.isBuffer(obj)
- Buffer.byteLength(string, encoding='utf8')
- buffer.length
- buffer.copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
- buffer.slice(start, end=buffer.length)
- Streams 流
- Readable Stream 可讀流
- Writable Stream 可寫流
- Crypto 加密模塊
- crypto.createCredentials(details)
- crypto.createHash(algorithm)
- hash.update(data)
- crypto.createHmac(algorithm, key)
- hmac.update(data)
- crypto.createCipher(algorithm, key)
- cipher.update(data, input_encoding='binary', output_encoding='binary')
- crypto.createDecipher(algorithm, key)
- decipher.update(data, input_encoding='binary', output_encoding='binary')
- crypto.createSign(algorithm)
- signer.update(data)
- signer.sign(private_key, output_format='binary')
- crypto.createVerify(algorithm)
- verifier.update(data)
- verifier.verify(cert, signature, signature_format='binary')
- TLS (SSL) TLS (SSL)模塊
- File System 文件系統模塊
- fs.rename(path1, path2, [callback])
- fs.renameSync(path1, path2)
- fs.truncate(fd, len, [callback])
- fs.truncateSync(fd, len)
- fs.chmod(path, mode, [callback])
- fs.chmodSync(path, mode)
- fs.stat(path, [callback])
- fs.lstat(path, [callback])
- fs.fstat(fd, [callback])
- fs.statSync(path)
- fs.lstatSync(path)
- fs.fstatSync(fd)
- fs.link(srcpath, dstpath, [callback])
- fs.linkSync(srcpath, dstpath)
- fs.symlink(linkdata, path, [callback])
- fs.symlinkSync(linkdata, path)
- fs.readlink(path, [callback])
- fs.readlinkSync(path)
- fs.realpath(path, [callback])
- fs.realpathSync(path)
- fs.unlink(path, [callback])
- fs.unlinkSync(path)
- fs.rmdir(path, [callback])
- fs.rmdirSync(path)
- fs.mkdir(path, mode, [callback])
- fs.mkdirSync(path, mode)
- fs.readdir(path, [callback])
- fs.readdirSync(path)
- fs.close(fd, [callback])
- fs.closeSync(fd)
- fs.open(path, flags, mode=0666, [callback])
- fs.openSync(path, flags, mode=0666)
- fs.utimes(path, atime, mtime, callback)
- fs.utimesSync(path, atime, mtime)
- fs.futimes(path, atime, mtime, callback)
- fs.futimesSync(path, atime, mtime)
- fs.write(fd, buffer, offset, length, position, [callback])
- fs.writeSync(fd, buffer, offset, length, position)
- fs.writeSync(fd, str, position, encoding='utf8')
- fs.read(fd, buffer, offset, length, position, [callback])
- fs.readSync(fd, buffer, offset, length, position)
- fs.readSync(fd, length, position, encoding)
- fs.readFile(filename, [encoding], [callback])
- fs.readFileSync(filename, [encoding])
- fs.writeFile(filename, data, encoding='utf8', [callback])
- fs.writeFileSync(filename, data, encoding='utf8')
- fs.watchFile(filename, [options], listener)
- fs.unwatchFile(filename)
- fs.Stats
- fs.ReadStream
- fs.WriteStream
- Path 路徑模塊
- net 網絡模塊
- net.createServer([options], [connectionListener])
- net.createConnection(arguments...)
- net.Server
- net.Socket
- new net.Socket([options])
- socket.connect(port, [host], [callback])
- socket.connect(path, [callback])
- socket.bufferSize
- socket.setEncoding(encoding=null)
- socket.setSecure()
- socket.write(data, [encoding], [callback])
- socket.write(data, [encoding], [fileDescriptor], [callback])
- socket.end([data], [encoding])
- socket.destroy()
- socket.pause()
- socket.resume()
- socket.setTimeout(timeout, [callback])
- socket.setNoDelay(noDelay=true)
- socket.setKeepAlive(enable=false, [initialDelay])
- socket.remoteAddress
- net.isIP
- DNS DNS模塊
- dns.lookup(domain, family=null, callback)
- dns.resolve(domain, rrtype='A', callback)
- dns.resolve4(domain, callback)
- dns.resolve6(domain, callback)
- dns.resolveMx(domain, callback)
- dns.resolveTxt(domain, callback)
- dns.resolveSrv(domain, callback)
- dns.reverse(ip, callback)
- UDP / Datagram Sockets 數據報套接字模塊
- dgram.createSocket(type, [callback])
- dgram.send(buf, offset, length, path, [callback])
- dgram.send(buf, offset, length, port, address, [callback])
- dgram.bind(path)
- dgram.bind(port, [address])
- dgram.close()
- dgram.address()
- dgram.setBroadcast(flag)
- dgram.setTTL(ttl)
- dgram.setMulticastTTL(ttl)
- dgram.setMulticastLoopback(flag)
- dgram.addMembership(multicastAddress, [multicastInterface])
- dgram.dropMembership(multicastAddress, [multicastInterface])
- HTTP HTTP模塊
- http.Server
- http.ServerRequest
- http.ServerResponse
- http.request(options, callback)
- http.get(options, callback)
- http.Agent
- http.getAgent(host, port)
- http.ClientRequest
- http.ClientResponse
- https.Server
- https.createServer
- https.request(options, callback)
- https.get(options, callback)
- URL URL模塊
- Query String 查詢字符串模塊
- REPL 交互式解釋器
- Child Processes 子進程
- Assert 斷言模塊
- assert.fail(actual, expected, message, operator)
- assert.ok(value, [message])
- assert.equal(actual, expected, [message])
- assert.notEqual(actual, expected, [message])
- assert.deepEqual(actual, expected, [message])
- assert.notDeepEqual(actual, expected, [message])
- assert.strictEqual(actual, expected, [message])
- assert.notStrictEqual(actual, expected, [message])
- assert.throws(block, [error], [message])
- assert.doesNotThrow(block, [error], [message])
- assert.ifError(value)
- TTY 終端模塊
- os Module 操作系統模塊
- Debugger 調試器
Appendixes 附錄
Synopsis 概要
An example of a web server written with Node which responds with 'HelloWorld':
下邊是一個用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/');
To run the server, put the code into a file called example.js
and executeit with the node program
要運行這個服務器程序,只要將上述代碼保存為文件example.js
并用node程序執行此文件:
> node example.js
Server running at http:
All of the examples in the documentation can be run similarly.
此文檔中所有例子均可用同樣的方法運行。## Global Objects 全局對象
These object are available in the global scope and can be accessed from anywhere.
這些對象在全局范圍內均可用,你可以在任何位置訪問這些對象。
global
The global namespace object.
全局命名空間對象
In browsers, the top-level scope is the global scope. That means that inbrowsers if you're in the global scopevar something
will define a globalvariable. In Node this is different. The top-level scope is not the globalscope;var something
inside a Node module will be local to that module.
在瀏覽器中,頂級作用域為全局作用域,在全局作用域下通過var something
即定義了一個全局變量。但是在Node中并不如此,頂級作用域并非是全局作用域,在Node模塊中通過var something
定義的變量僅作用于該模塊。
process
The process object. See the 'process object' section.
進程對象,參見'process object'章節。
require()
To require modules. See the 'Modules' section.
加載模塊,參見'Modules'章節。
require.resolve()
Use the internal require()
machinery to look up the location of a module,but rather than loading the module, just return the resolved filename.
使用內部函數require()
的機制查找一個模塊的位置,而不用加載模塊,只是返回解析后的文件名。
require.paths
An array of search paths for require()
. This array can be modified to addcustom paths.
require()
的搜索路徑數組,你可以修改該數組添加自定義的搜索路徑。
Example: add a new path to the beginning of the search list
例如:將一個新的搜索路徑插入到搜索列表的頭部。
require.paths.unshift('/usr/local/node');
__filename
The filename of the script being executed. This is the absolute path, and not necessarilythe same filename passed in as a command line argument.
當前正在執行的腳本的文件名。這是一個絕對路徑,可能會和命令行參數中傳入的文件名不同。
Example: running node example.js
from /Users/mjr
例如:在目錄/Users/mjr
下運行node example.js
console.log(__filename);
__dirname
The dirname of the script being executed.
當前正在執行腳本所在的目錄名。
Example: running node example.js
from /Users/mjr
例如:在目錄/Users/mjr
下運行node example.js
console.log(__dirname);
module
A reference to the current module. In particularmodule.exports
is the same as theexports
object. See src/node.js
for more information.
指向當前模塊的引用。特別的,當你通過module.exports
和exports
兩種方式訪問的將是同一個對象,參見src/node.js
。
Timers 定時器
setTimeout(callback, delay, [arg], [...])
To schedule execution of callback
after delay
milliseconds. Returns atimeoutId
for possible use withclearTimeout()
. Optionally, you canalso pass arguments to the callback.
設定一個delay
毫秒后執行callback
回調函數的計劃。返回值timeoutId
可被用于clearTimeout()
。可以設定要傳遞給回調函數的參數。
clearTimeout(timeoutId)
Prevents a timeout from triggering.
清除定時器,阻止指定的timeout(超時)定時器被觸發。
setInterval(callback, delay, [arg], [...])
To schedule the repeated execution of callback
every delay
milliseconds.Returns aintervalId
for possible use with clearInterval()
. Optionally,you can also pass arguments to the callback.
設定一個每delay
毫秒重復執行callback
回調函數的計劃。返回值intervalId
可被用于clearInterval()
。可以設定要傳遞給回調函數的參數。
clearInterval(intervalId)
Stops a interval from triggering.
清除定時器,阻止指定的interval(間隔)定時器被觸發。## Modules 模塊
Node uses the CommonJS module system.Node has a simple module loading system. In Node, files and modules are inone-to-one correspondence. As an example,foo.js
loads the modulecircle.js
in the same directory.
Node使用CommonJS模塊系統。Node有一個簡單的模塊裝載系統,在Node中,文件和模塊是一一對應的。下面的例子展示了foo.js
文件如何在相同的目錄中加載circle.js
模塊。
The contents of foo.js
:
foo.js
的內容為:
var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is '
+ circle.area(4));
The contents of circle.js
:
circle.js
的內容為:
var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
The module circle.js
has exported the functions area()
andcircumference()
. To export an object, add to the specialexports
object.
circle.js
模塊輸出了area()
和circumference()
兩個函數,為了以對象的形式輸出,需將要輸出的函數加入到一個特殊的exports
對像中。
Variableslocal to the module will be private. In this example the variable PI
isprivate to circle.js
.
模塊的本地變量是私有的。在上面的例子中,變量PI
就是circle.js
私有的。
Core Modules 核心模塊
Node has several modules compiled into the binary. These modules aredescribed in greater detail elsewhere in this documentation.
Node有一些編譯成二進制的模塊。這些模塊在這篇文檔的其他地方有詳細描述。
The core modules are defined in node's source in the lib/
folder.
核心模塊在node源代碼中的lib文件夾下。
Core modules are always preferentially loaded if their identifier ispassed to require()
. For instance, require('http')
will alwaysreturn the built in HTTP module, even if there is a file by that name.
核心模塊總是被優先加載,如果它們的標識符被require()
調用。例如,require('http')
將總是返回內建的HTTP模塊,即便又一個同名文件存在。
File Modules 文件模塊
If the exact filename is not found, then node will attempt to load therequired filename with the added extension of.js
, and then .node
..js
files are interpreted as JavaScript text files, and.node
filesare interpreted as compiled addon modules loaded with dlopen
.
如果沒有找到確切的文件名,node將嘗試以追加擴展名.js
后的文件名讀取文件,如果還是沒有找到則嘗試追加擴展名.node
。.js
文件被解釋為JavaScript格式的純文本文件,.node
文件被解釋為編譯后的addon(插件)模塊,并使用dlopen
來加載。
A module prefixed with '/'
is an absolute path to the file. Forexample,require('/home/marco/foo.js')
will load the file at/home/marco/foo.js
.
以'/'
為前綴的模塊是一個指向文件的絕對路徑,例如require('/home/marco/foo.js')
將加載文件/home/marco/foo.js
。
A module prefixed with './'
is relative to the file calling require()
.That is, circle.js
must be in the same directory asfoo.js
forrequire('./circle')
to find it.
以'./'
為前綴的模塊是指向文件的相對路徑,相對于調用require()
的文件。也就是說為了使require('./circle')
能找到正確的文件,circle.js
必須位于與foo.js
相同的路徑之下。
Without a leading '/' or './' to indicate a file, the module is either a"core module" or is loaded from anode_modules
folder.
如果標明一個文件時沒有 '/' 或 './'前綴,該模塊或是"核心模塊",或者位于 node_modules
目錄中。
Loading from `node_modules` Folders 從 `node_modules` 目錄中加載
If the module identifier passed to require()
is not a native module,and does not begin with'/'
, '../'
, or './'
, then node starts at theparent directory of the current module, and adds/node_modules
, andattempts to load the module from that location.
如果傳遞到 require()
的模塊標識符不是一個核心模塊,并且不是以'/'
,'../'
或'./'
開頭,node將從當前模塊的父目錄開始,在其/node_modules
子目錄中加載該模塊。
If it is not found there, then it moves to the parent directory, and soon, until either the module is found, or the root of the tree isreached.
如果在那里沒有找到,就轉移到上一級目錄,依此類推,直到找到該模塊或到達目錄樹的根結點。
For example, if the file at '/home/ry/projects/foo.js'
calledrequire('bar.js')
, then node would look in the following locations, inthis order:
例如,如果在文件 '/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
This allows programs to localize their dependencies, so that they do notclash.
這允許程序本地化他們的依賴關系,避免發生沖突。
Optimizations to the `node_modules` Lookup Process 優化 `node_modules` 的查找過程
When there are many levels of nested dependencies, it is possible forthese file trees to get fairly long. The following optimizations are thusmade to the process.
如果有很多級的嵌套信賴,文件樹會變得相當的長,下面是對這一過程的一些優化。
First, /node_modules
is never appended to a folder already ending in/node_modules
.
首先, /node_modules
不要添加到以 /node_modules
結尾的目錄上。
Second, if the file calling require()
is already inside a node_modules
hierarchy, then the top-mostnode_modules
folder is treated as theroot of the search tree.
其次,如果調用require()
的文件已經位于一個node_modules
層次中,最上級的node_modules
目錄將被作為搜索的根。
For example, if the file at'/home/ry/projects/foo/node_modules/bar/node_modules/baz/quux.js'
calledrequire('asdf.js')
, then node would search the followinglocations:
例如,如果文件'/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
Folders as Modules 目錄作為模塊
It is convenient to organize programs and libraries into self-containeddirectories, and then provide a single entry point to that library.There are three ways in which a folder may be passed torequire()
asan argument.
很方便將程序或庫組織成自包含的目錄,并提供一個單獨的入口指向那個庫。有三種方式可以將一個子目錄作為參數傳遞給 require()
。
The first is to create a package.json
file in the root of the folder,which specifies amain
module. An example package.json file mightlook like this:
第一種方法是在目錄的根下創建一個名為package.json
的文件,它指定了一個main
模塊。一個package.jso文件的例子如下面所示:
{ "name" : "some-library",
"main" : "./lib/some-library.js" }
If this was in a folder at ./some-library
, thenrequire('./some-library')
would attempt to load./some-library/lib/some-library.js
.
如果此文件位于./some-library
目錄中,require('./some-library')
將試圖加載文件./some-library/lib/some-library.js
。
This is the extent of Node's awareness of package.json files.
這是Node感知package.json文件的范圍。
If there is no package.json file present in the directory, then nodewill attempt to load anindex.js
or index.node
file out of thatdirectory. For example, if there was no package.json file in the aboveexample, thenrequire('./some-library')
would attempt to load:
如果在目錄中沒有package.json文件,node將試圖在該目錄中加載index.js
或 index.node
文件。例如,在上面的例子中沒有 package.json文件,require('./some-library')
將試圖加載:
./some-library/index.js
./some-library/index.node
Caching 緩存
Modules are cached after the first time they are loaded. This means(among other things) that every call torequire('foo')
will getexactly the same object returned, if it would resolve to the same file.
模塊在第一次加載后將被緩存。這意味著(類似其他緩存)每次調用require('foo')
如果解析到相同的文件,那么將返回同一個對象。
All Together... 總結一下...
To get the exact filename that will be loaded when require()
is called, usetherequire.resolve()
function.
可使用require.resolve()
函數,獲得調用require()
時將加載的準確的文件名。
Putting together all of the above, here is the high-level algorithmin pseudocode of what require.resolve does:
綜上所述,這里以偽代碼的形式給出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
Loading from the `require.paths` Folders 從`require.paths`目錄中加載
In node, require.paths
is an array of strings that represent paths tobe searched for modules when they are not prefixed with'/'
, './'
, or'../'
. For example, if require.paths were set to:
在node中,require.paths
是一個保存模塊搜索路徑的字符串數組。當模塊不以'/'
,'./'
或'../'
為前綴時,將從此數組中的路徑里進行搜索。例如,如果require.paths如下設置:
[ '/home/micheil/.node_modules',
'/usr/local/lib/node_modules' ]
Then calling require('bar/baz.js')
would search the followinglocations:
當調用require('bar/baz.js')
時將搜索下列位置:
- 1:
'/home/micheil/.node_modules/bar/baz.js'
- 2:
'/usr/local/lib/node_modules/bar/baz.js'
The require.paths
array can be mutated at run time to alter thisbehavior.
可以在運行時改變require.paths
數組的內容,以改變路徑搜索行為。
It is set initially from the NODE_PATH
environment variable, which isa colon-delimited list of absolute paths. In the previous example,theNODE_PATH
environment variable might have been set to:
此數組使用NODE_PATH
環境變量進行初始化,此環境變量是冒號分割的路徑列表。在之前的例子中,NODE_PATH
環境變量被設置為如下內容:
/home/micheil/.node_modules:/usr/local/lib/node_modules
Loading from the require.paths
locations is only performed if themodule could not be found using thenode_modules
algorithm above.Global modules are lower priority than bundled dependencies.
只有當使用上面介紹的node_modules
算法無法找到模塊時,才會從require.paths
地址里進行加載。全局模塊比綁定抵賴的模塊優先級低。
**Note:** Please Avoid Modifying `require.paths` **注意:** 請不要修改`requires.paths`
For compatibility reasons, require.paths
is still given first priorityin the module lookup process. However, it may disappear in a futurerelease.
由于兼容性的原因,require.paths
仍然在模塊查詢過程中處于第一優先級。然而,在未來發布的版本中這個問題將被解決。
While it seemed like a good idea at the time, and enabled a lot ofuseful experimentation, in practice a mutablerequire.paths
list isoften a troublesome source of confusion and headaches.
雖然在當時看起來這是個好注意,可以支持很多有用的實驗手段。但在實踐中發現,修改require.paths
列表往往是造成混亂和麻煩的源頭。
Setting `require.paths` to some other value does nothing. 將`require.paths`設為其他值不會產生任何作用
This does not do what one might expect:
下述做法不會其他你期望的任何效果:
require.paths = [ '/usr/lib/node' ];
All that does is lose the reference to the actual node module lookuppaths, and create a new reference to some other thing that isn't usedfor anything.
這么做將會丟失對真正的模塊搜索路徑列表對象的引用,同時指向了一個新創建的對象,而這個對象將不會其任何作用。
Putting relative paths in `require.paths` is... weird. 不建議在`require.paths`中發入相對路徑
If you do this:
如果你這樣做:
require.paths.push('./lib');
then it does not add the full resolved path to where ./lib
is on the filesystem. Instead, it literally adds'./lib'
,meaning that if you do require('y.js')
in /a/b/x.js
, then it'll lookin /a/b/lib/y.js
. If you then did require('y.js')
in/l/m/n/o/p.js
, then it'd look in /l/m/n/o/lib/y.js
.
這樣只會添加'./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
。
In practice, people have used this as an ad hoc way to bundledependencies, but this technique is brittle.
在實踐中,有用戶使用這種特別的方式來實現綁定依賴,但這種方式是很脆弱的。
Zero Isolation 零隔離
There is (by regrettable design), only one require.paths
array used byall modules.
由于設計的失誤,所有模塊都共享同一個require.paths
數組。
As a result, if one node program comes to rely on this behavior, it maypermanently and subtly alter the behavior of all other node programs inthe same process. As the application stack grows, we tend to assemblefunctionality, and it is a problem with those parts interact in waysthat are difficult to predict.
造成的結果是,如果一個node程序依賴于這種行為,它將永久的并且隱蔽的改變處在同個進程內的所有其他node程序的行為。一旦應用程序變大,我們往往進行功能集成,各部分功能以不可預料的方式互相影響將成為問題。
Addenda: Package Manager Tips 附錄:包管理技巧
The semantics of Node's require()
function were designed to be generalenough to support a number of sane directory structures. Package managerprograms such asdpkg
, rpm
, and npm
will hopefully find it possible tobuild native packages from Node modules without modification.
Node的require()
函數的語義被設計的足夠通用化,以支持各種常規目錄結構。包管理程序如 dpkg
,rpm
和npm
將不用修改就能夠從Node模塊構建本地包。
Below we give a suggested directory structure that could work:
接下來我們將給你一個可行的目錄結構建議:
Let's say that we wanted to have the folder at/usr/lib/node/<some-package>/<some-version>
hold the contents of aspecific version of a package.
假設我們希望將一個包的指定版本放在/usr/lib/node/<some-package>/<some-version>
目錄中。
Packages can depend on one another. In order to install package foo
, youmay have to install a specific version of packagebar
. The bar
packagemay itself have dependencies, and in some cases, these dependencies may evencollide or form cycles.
包可以依賴于其他包。為了安裝包foo
,可能需要安裝包bar
的一個指定版本。包bar
也可能有依賴關系,在一些情況下依賴關系可能發生沖突或形成循環。
Since Node looks up the realpath
of any modules it loads (that is,resolves symlinks), and then looks for their dependencies in thenode_modules
folders as described above, this situation is very simple toresolve with the following architecture:
因為Node會查找它所加載的模塊的真實路徑
(也就是說會解析符號鏈接),然后按照上文描述的方式在node_modules
目錄中尋找依賴關系,所以可以使用如下的目錄結構解決這個問題:
/usr/lib/node/foo/1.2.3/
- Contents of the foo
package, version 1.2.3./usr/lib/node/foo/1.2.3/
- 包foo
的1.2.3版本內容。/usr/lib/node/bar/4.3.2/
- Contents of the bar
package thatfoo
depends on./usr/lib/node/bar/4.3.2/
- 包foo
依賴的包bar
的內容。/usr/lib/node/foo/1.2.3/node_modules/bar
- Symbolic link to/usr/lib/node/bar/4.3.2/
./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/*
- Symbolic links to the packagesthatbar
depends on./usr/lib/node/bar/4.3.2/node_modules/*
- 指向包bar
所依賴的包的符號鏈接。
Thus, even if a cycle is encountered, or if there are dependencyconflicts, every module will be able to get a version of its dependencythat it can use.
因此即便存在循環依賴或依賴沖突,每個模塊還是可以獲得他所依賴的包的一個可用版本。
When the code in the foo
package does require('bar')
, it will get theversion that is symlinked into/usr/lib/node/foo/1.2.3/node_modules/bar
.Then, when the code in the bar
package calls require('quux')
, it'll getthe version that is symlinked into/usr/lib/node/bar/4.3.2/node_modules/quux
.
當包foo
中的代碼調用require('bar')
,將獲得符號鏈接/usr/lib/node/foo/1.2.3/node_modules/bar
指向的版本。同樣,當包bar
中的代碼調用require('queue')
,降火的符號鏈接/usr/lib/node/bar/4.3.2/node_modules/quux
指向的版本。
Furthermore, to make the module lookup process even more optimal, ratherthan putting packages directly in/usr/lib/node
, we could put them in/usr/lib/node_modules/<name>/<version>
. Then node will not botherlooking for missing dependencies in/usr/node_modules
or /node_modules
.
為了進一步優化模塊搜索過程,不要將包直接放在/usr/lib/node
目錄中,而是將它們放在/usr/lib/node_modules/<name>/<version>
目錄中。這樣在依賴的包找不到的情況下,就不會一直尋找到/usr/node_modules
目錄或/node_modules
目錄中了。
In order to make modules available to the node REPL, it might be useful toalso add the/usr/lib/node_modules
folder to the $NODE_PATH
environmentvariable. Since the module lookups usingnode_modules
folders are allrelative, and based on the real path of the files making the calls torequire()
, the packages themselves can be anywhere.
為了使模塊在node REPL中可用,你可能需要將/usr/lib/node_modules
目錄加入到$NODE_PATH
環境變量中。由于在node_modules
目錄中搜索模塊使用的是相對路徑,基于調用require()
的文件所在真實路徑,因此包本身可以放在任何位置。## Addons 擴展插件
Addons are dynamically linked shared objects. They can provide glue to C andC++ libraries. The API (at the moment) is rather complex, involvingknowledge of several libraries:
擴展插件(Addons)是動態鏈接的共享對象,這些對象提供了使用C/C++類庫的能力。由于涉及了多個類庫導致了這類API目前比較繁雜,主要包括下述幾個主要類庫:
-
V8 JavaScript, a C++ library. Used for interfacing with JavaScript:creating objects, calling functions, etc. Documented mostly in thev8.h
header file (deps/v8/include/v8.h
in the Node source tree).
V8 JavaScript,C++類庫,作為JavaScript的接口類,主要用于創建對象、調用方法等功能。大部分功能在頭文件v8.h
(在node文件夾下的路徑為deps/v8/include/v8.h
)中有詳細文檔。
-
libev, C event loop library. Anytime one needs to wait for a filedescriptor to become readable, wait for a timer, or wait for a signal toreceived one will need to interface with libev. That is, if you performany I/O, libev will need to be used. Node uses the EV_DEFAULT
eventloop. Documentation can be found here.
libev,基于C的事件循環庫。當需要等待文件描述(file descriptor)為可讀時,等待定時器時,或者等待接受信號時,會需要調用libev庫。也可以說,任何IO操作都需要調用libev庫。Node使用EV_DEFAULT
事件循環機制。在這里可以查閱相關文檔。
-
libeio, C thread pool library. Used to execute blocking POSIX systemcalls asynchronously. Mostly wrappers already exist for such calls, insrc/file.cc
so you will probably not need to use it. If you do need it,look at the header filedeps/libeio/eio.h
.
libeio,基于C的線程池庫,用于以異步方式執行阻塞式POSIX系統調用。因為大部分這類調用都在src/file.cc
中被封裝了,你一般不需要直接使用libeio。如果必須使用該類庫時,可查看其頭文件deps/libeio/eio.h
。
-
Internal Node libraries. Most importantly is the node::ObjectWrap
class which you will likely want to derive from.
內部Node庫。在該庫中,最重要的類是我們可能用于進行派生的node::ObjectWrap
基類。
-
Others. Look in deps/
for what else is available.
其他的一些類庫同樣可以在deps/
中找到。
Node statically compiles all its dependencies into the executable. Whencompiling your module, you don't need to worry about linking to any of theselibraries.
Node已將所有依賴關系靜態地編譯成可執行文件,因此我們在編譯自己的組件時不需要擔心和這些類庫的鏈接問題。
To get started let's make a small Addon which does the following except inC++:
讓我們著手編寫一個Addon的小例子,來達到如下模塊同樣的效果:
exports.hello = 'world';
To get started we create a file hello.cc
:
首先我們需要創建一個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. Todo this we create a file calledwscript
which is python code and lookslike this:
這些源碼會編譯成一個二進制的Addon文件hello.node
。為此我們用python編寫如下的名為wscript
的文件:
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 filebuild/default/hello.node
which is our Addon.
運行node-waf configure build
,我們就創建了一個Addon實例build/default/hello.node
。
node-waf
is just WAF, the python-based build system.node-waf
isprovided for the ease of users.
node-waf
就是WAF,,一種基于python的編譯系統,而node-waf
更加易于使用。
All Node addons must export a function called init
with this signature:
另外,在Node中任何的Addon必須使用輸出一個如下聲明的init
函數:
extern 'C' void init (Handle<Object> target)
For the moment, that is all the documentation on addons. Please seehttp://github.com/ry/node_postgres for a real example.
目前關于addon的所有文檔就是這些。另外,在http://github.com/ry/node_postgres中還提供了一個Addon的實例。## process 進程
The process
object is a global object and can be accessed from anywhere.
process
對象是一個全局對象,可以在任何地方訪問它。
It is an instance of EventEmitter
.
它是EventEmitter
事件觸發器類型的一個實例。
Event: 'exit' 事件:'exit'
function () {}
Emitted when the process is about to exit. This is a good hook to performconstant time checks of the module's state (like for unit tests). The mainevent loop will no longer be run after the 'exit' callback finishes, sotimers may not be scheduled.
當進程對象要退出時會觸發此方法,這是檢查模塊狀態(比如單元測試)的好時機。當'exit'被調用完成后主事件循環將終止,所以計時器將不會按計劃執行。
Example of listening for exit
:
監聽exit
行為的示例:
process.on('exit', function () {
process.nextTick(function () {
console.log('This will not run');
});
console.log('About to exit.');
});
Event: 'uncaughtException' 事件:'uncaughtException'
function (err) { }
Emitted when an exception bubbles all the way back to the event loop. If alistener is added for this exception, the default action (which is to printa stack trace and exit) will not occur.
當一個異常信息一路冒出到事件循環時,該方法被觸發。如果該異常有一個監聽器,那么默認的行為(即打印一個堆棧軌跡并退出)將不會發生。
Example of listening for uncaughtException
:
監聽uncaughtException
事件的示例:
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
});
setTimeout(function () {
console.log('This will still run.');
}, 500);
nonexistentFunc();
console.log('This will not run.');
Note that uncaughtException
is a very crude mechanism for exceptionhandling. Using try / catch in your program will give you more control overyour program's flow. Especially for server programs that are designed tostay running forever,uncaughtException
can be a useful safety mechanism.
注意:就異常處理來說,uncaughtException
是一個很粗糙的機制。在程序中使用try/catch可以更好好控制程序流程。而在服務器編程中,因為要持續運行,uncaughtException
還是一個很有用的安全機制。
Signal Events 信號事件
function () {}
Emitted when the processes receives a signal. See sigaction(2) for a list ofstandard POSIX signal names such as SIGINT, SIGUSR1, etc.
該事件會在進程接收到一個信號時被觸發。可參見sigaction(2)中的標準POSIX信號名稱列表,比如SIGINT,SIGUSR1等等。
Example of listening for SIGINT
:
監聽 SIGINT
的示例:
process.stdin.resume();
process.on('SIGINT', function () {
console.log('Got SIGINT. Press Control-D to exit.');
});
An easy way to send the SIGINT
signal is with Control-C
in most terminalprograms.
在大多數終端程序中,一個簡易發送SIGINT
信號的方法是在使用Control-C
命令操作。
process.stdout
A Writable Stream
to stdout
.
一個指向標準輸出stdout
的Writable Stream
可寫流。
Example: the definition of console.log
示例:console.log
的定義。
console.log = function (d) {
process.stdout.write(d + '\n');
};
process.stderr
A writable stream to stderr. Writes on this stream are blocking.
一個指向錯誤的可寫流,在這個流上的寫操作是阻塞式的。
process.stdin
A Readable Stream
for stdin. The stdin stream is paused by default, so onemust callprocess.stdin.resume()
to read from it.
一個到標準輸入的可讀流Readable Stream
。默認情況下標準輸入流是暫停的,要從中讀取內容需要調用方法process.stdin.resume()
。
Example of opening standard input and listening for both events:
示例:打開標準輸入與監聽兩個事件:
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');
});
process.argv
An array containing the command line arguments. The first element will be'node', the second element will be the name of the JavaScript file. Thenext elements will be any additional command line arguments.
一個包含命令行參數的數組。第一個元素是'node',第二個元素是JavaScript文件的文件名。接下來的元素則是附加的命令行參數。
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
This will generate:
這產生如下的信息:
$ 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
process.execPath
This is the absolute pathname of the executable that started the process.
這是一個啟動該進程的可執行程序的絕對路徑名。
Example:
例如:
/usr/local/bin/node
process.chdir(directory)
Changes the current working directory of the process or throws an exception if that fails.
改變進程的當前工作目錄,如果操作失敗則拋出異常。
console.log('Starting directory: ' + process.cwd());
try {
process.chdir('/tmp');
console.log('New directory: ' + process.cwd());
}
catch (err) {
console.log('chdir: ' + err);
}
process.cwd()
Returns the current working directory of the process.
返回進程的當前工作目錄。
console.log('Current directory: ' + process.cwd());
process.env
An object containing the user environment. See environ(7).
一個包括用戶環境的對象。可參見environ(7)。
process.exit(code=0)
Ends the process with the specified code
. If omitted, exit uses the'success' code0
.
用指定的code
代碼結束進程。如果不指定,退出時將使用'success'(成功)代碼 0
。
To exit with a 'failure' code:
以'failure'(失敗)代碼退出的示例:
process.exit(1);
The shell that executed node should see the exit code as 1.
執行node的shell會把退出代碼視為1。
process.getgid()
Gets the group identity of the process. (See getgid(2).)This is the numerical group id, not the group name.
獲取進程的群組標識(詳見getgid(2))。這是一個數字的群組ID,不是群組名稱。
console.log('Current gid: ' + process.getgid());
process.setgid(id)
Sets the group identity of the process. (See setgid(2).) This accepts eithera numerical ID or a groupname string. If a groupname is specified, this methodblocks while resolving it to a numerical ID.
設置進程的群組標識(詳見getgid(2))。參數可以是一個數字ID或者群組名字符串。如果指定了一個群組名,這個方法會阻塞等待將群組名解析為數字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);
}
process.getuid()
Gets the user identity of the process. (See getuid(2).)This is the numerical userid, not the username.
獲取進程的用戶ID(詳見getgid(2))。這是一個數字用戶ID,不是用戶名。
console.log('Current uid: ' + process.getuid());
process.setuid(id)
Sets the user identity of the process. (See setuid(2).) This accepts eithera numerical ID or a username string. If a username is specified, this methodblocks while resolving it to a numerical ID.
設置進程的用戶ID(詳見getgid(2))。參數可以使一個數字ID或者用戶名字符串。如果指定了一個用戶名,那么該方法會阻塞等待將用戶名解析為數字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);
}
process.version
A compiled-in property that exposes NODE_VERSION
.
一個編譯內置的屬性,用于顯示NODE_VERSION
(Node版本)。
console.log('Version: ' + process.version);
process.installPrefix
A compiled-in property that exposes NODE_PREFIX
.
一個編譯內置的屬性,用于顯示NODE_PREFIX
(Node安裝路徑前綴)。
console.log('Prefix: ' + process.installPrefix);
process.kill(pid, signal='SIGTERM')
Send a signal to a process. pid
is the process id and signal
is thestring describing the signal to send. Signal names are strings like'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGTERM'.See kill(2) for more information.
發送一個信號到進程。pid
是進程的ID,參數signal
是欲發送信號的字符串描述。信號名稱是像'SIGINT'或者'SIGUSR1'這樣的字符串。如果參數signal
忽略,則信號為'SIGTERM'。詳見kill(2)。
Note that just because the name of this function is process.kill
, it isreally just a signal sender, like thekill
system call. The signal sentmay do something other than kill the target process.
注意該函數名為process.kill
,實際上也就像kill
系統調用一樣僅僅是一個信號發送器。發送的信號可能是要終止目標進程,也可能是實現其他不同的目的。
Example of sending a signal to yourself:
一個給自己發送信號的示例:
process.on('SIGHUP', function () {
console.log('Got SIGHUP signal.');
});
setTimeout(function () {
console.log('Exiting.');
process.exit(0);
}, 100);
process.kill(process.pid, 'SIGHUP');
process.pid
The PID of the process.
進程的PID。
console.log('This process is pid ' + process.pid);
process.title
Getter/setter to set what is displayed in 'ps'.
獲取或設置在'ps'命令中顯示的進程的標題。
What platform you're running on. 'linux2'
, 'darwin'
, etc.
運行Node的平臺信息,如'linux2',
'darwin'`等等。
console.log('This platform is ' + process.platform);
process.memoryUsage()
Returns an object describing the memory usage of the Node process.
返回一個描述Node進程內存使用情況的對象。
var util = require('util');
console.log(util.inspect(process.memoryUsage()));
This will generate:
這會生成如下信息:
{ rss: 4935680,
vsize: 41893888,
heapTotal: 1826816,
heapUsed: 650472 }
heapTotal
and heapUsed
refer to V8's memory usage.
heapTotal
與heapUsed
指V8的內存使用情況。
process.nextTick(callback)
On the next loop around the event loop call this callback.This is not a simple alias tosetTimeout(fn, 0)
, it's much moreefficient.
在事件循環的下一次循環中調用callback回調函數。這不是setTimeout(fn, 0)
的一個別名,因為它有效率多了。
process.nextTick(function () {
console.log('nextTick callback');
});
process.umask([mask])
Sets or reads the process's file mode creation mask. Child processes inheritthe mask from the parent process. Returns the old mask ifmask
argument isgiven, otherwise returns the current mask.
設置或者讀取進程的文件模式創建掩碼。子進程從父進程中繼承這個掩碼。如果設定了參數mask
那么返回舊的掩碼,否則返回當前的掩碼。
var oldmask, newmask = 0644;
oldmask = process.umask(newmask);
console.log('Changed umask from: ' + oldmask.toString(8) +
' to ' + newmask.toString(8));
util 工具模塊
These functions are in the module 'util'
. Use require('util')
to accessthem.
下列函數屬于'util'
(工具)模塊,可使用require('util')
訪問它們。
util.debug(string)
A synchronous output function. Will block the process andoutput string
immediately tostderr
.
這是一個同步輸出函數,將string
參數的內容實時輸出到stderr
標準錯誤。調用此函數時將阻塞當前進程直到輸出完成。
require('util').debug('message on stderr');
util.log(string)
Output with timestamp on stdout
.
將string
參數的內容加上當前時間戳,輸出到stdout
標準輸出。
require('util').log('Timestmaped message.');
util.inspect(object, showHidden=false, depth=2)
Return a string representation of object
, which is useful for debugging.
以字符串形式返回object
對象的結構信息,這對程序調試非常有幫助。
If showHidden
is true
, then the object's non-enumerable properties will beshown too.
如果showHidden
參數設置為true
,則此對象的不可枚舉屬性也會被顯示。
If depth
is provided, it tells inspect
how many times to recurse whileformatting the object. This is useful for inspecting large complicated objects.
可使用depth
參數指定inspect
函數在格式化對象信息時的遞歸次數。這對分析復雜對象的內部結構非常有幫助。
The default is to only recurse twice. To make it recurse indefinitely, passin null
for depth
.
默認情況下遞歸兩次,如果想要無限遞歸可將depth
參數設為null
。
Example of inspecting all properties of the util
object:
顯示util
對象所有屬性的例子如下:
var util = require('util');
console.log(util.inspect(util, true, null));
util.pump(readableStream, writableStream, [callback])
Experimental
實驗性的
Read the data from readableStream
and send it to the writableStream
.WhenwritableStream.write(data)
returns false
readableStream
will bepaused until thedrain
event occurs on the writableStream
. callback
getsan error as its only argument and is called whenwritableStream
is closed orwhen an error occurs.
從readableStream
參數所指定的可讀流中讀取數據,并將其寫入到writableStream
參數所指定的可寫流中。當writeableStream.write(data)
函數調用返回為false
時,readableStream
流將被暫停,直到在writableStream
流上發生drain
事件。當writableStream
流被關閉或發生一個錯誤時,callback
回調函數被調用。此回調函數只接受一個參數用以指明所發生的錯誤。
util.inherits(constructor, superConstructor)
Inherit the prototype methods from oneconstructorinto another. The prototype ofconstructor
will be set to a newobject created from superConstructor
.
將一個構造函數的原型方法繼承到另一個構造函數中。constructor
構造函數的原型將被設置為使用superConstructor
構造函數所創建的一個新對象。
As an additional convenience, superConstructor
will be accessiblethrough theconstructor.super_
property.
此方法帶來的額外的好處是,可以通過constructor.super_
屬性來訪問superConstructor
構造函數。
var util = require("util");
var events = require("events");
function MyStream() {
events.EventEmitter.call(this);
}
util.inherits(MyStream, events.EventEmitter);
MyStream.prototype.write = function(data) {
this.emit("data", data);
}
var stream = new MyStream();
console.log(stream instanceof events.EventEmitter);
console.log(MyStream.super_ === events.EventEmitter);
stream.on("data", function(data) {
console.log('Received data: "' + data + '"');
})
stream.write("It works!");
Events 事件模塊
Many objects in Node emit events: a net.Server
emits an event each timea peer connects to it, afs.readStream
emits an event when the file isopened. All objects which emit events are instances ofevents.EventEmitter
.You can access this module by doing: require("events");
Node引擎中很多對象都會觸發事件:例如net.Server
會在每一次有客戶端連接到它時觸發事件,又如fs.readStream
會在文件打開時觸發事件。所有能夠觸發事件的對象都是events.EventEmitter
的實例。你可以通過require("events");
訪問這個模塊。
Typically, event names are represented by a camel-cased string, however,there aren't any strict restrictions on that, as any string will be accepted.
通常情況下,事件名稱采用駝峰式寫法,不過目前并沒有對事件名稱作任何的限制,也就是說任何的字符串都可以被接受。
Functions can then be attached to objects, to be executed when an eventis emitted. These functions are calledlisteners.
可以將函數注冊給對象,使其在事件觸發時執行,此類函數被稱作監聽器。
events.EventEmitter
To access the EventEmitter class, require('events').EventEmitter
.
通過調用require('events').EventEmitter
,我們可以使用事件觸發器類。
When an EventEmitter
instance experiences an error, the typical action isto emit an'error'
event. Error events are treated as a special case in node.If there is no listener for it, then the default action is to print a stacktrace and exit the program.
當EventEmitter
事件觸發器遇到錯誤時,典型的處理方式是它將觸發一個'error'
事件。Error事件的特殊性在于:如果沒有函數處理這個事件,它將會輸出調用堆棧,并隨之退出應用程序。
All EventEmitters emit the event 'newListener'
when new listeners areadded.
當新的事件監聽器被添加時,所有的事件觸發器都將觸發名為'newListener'
的事件。
emitter.addListener(event, listener)
emitter.on(event, listener)
Adds a listener to the end of the listeners array for the specified event.
將一個監聽器添加到指定事件的監聽器數組的末尾。
server.on('connection', function (stream) {
console.log('someone connected!');
});
emitter.once(event, listener)
Adds a one time listener for the event. The listener isinvoked only the first time the event is fired, after whichit is removed.
為事件添加一次性的監聽器。該監聽器在事件第一次觸發時執行,過后將被移除。
server.once('connection', function (stream) {
console.log('Ah, we have our first user!');
});
emitter.removeListener(event, listener)
Remove a listener from the listener array for the specified event.Caution: changes array indices in the listener array behind the listener.
將監聽器從指定事件的監聽器數組中移除出去。小心:此操作將改變監聽器數組的下標。
var callback = function(stream) {
console.log('someone connected!');
};
server.on('connection', callback);
server.removeListener('connection', callback);
emitter.removeAllListeners(event)
Removes all listeners from the listener array for the specified event.
將指定事件的所有監聽器從監聽器數組中移除。
emitter.setMaxListeners(n)
By default EventEmitters will print a warning if more than 10 listeners areadded to it. This is a useful default which helps finding memory leaks.Obviously not all Emitters should be limited to 10. This function allowsthat to be increased. Set to zero for unlimited.
默認情況下當事件觸發器注冊了超過10個以上的監聽器時系統會打印警告信息,這個默認配置將有助于你查找內存泄露問題。很顯然并不是所有的事件觸發器都需要進行10個監聽器的限制,此函數允許你手動設置該數量值,如果值為0意味值沒有限制。
emitter.listeners(event)
Returns an array of listeners for the specified event. This array can bemanipulated, e.g. to remove listeners.
返回指定事件的監聽器數組對象,你可以對該數組進行操作,比如說刪除監聽器等。
server.on('connection', function (stream) {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection'));
emitter.emit(event, [arg1], [arg2], [...])
Execute each of the listeners in order with the supplied arguments.
以提供的參數作為監聽器函數的參數,順序執行監聽器列表中的每個監聽器函數。
Event: 'newListener' 事件:'newListener'
function (event, listener) { }
This event is emitted any time someone adds a new listener.
任何時候只要新的監聽器被添加時該事件就會觸發。
Buffers 緩沖器
Pure Javascript is Unicode friendly but not nice to binary data. Whendealing with TCP streams or the file system, it's necessary to handle octetstreams. Node has several strategies for manipulating, creating, andconsuming octet streams.
純Javascript語言是Unicode友好性的,但是難以處理二進制數據。在處理TCP流和文件系統時經常需要操作字節流。Node提供了一些列機制,用于操作、創建、以及消耗(consuming)字節流。
Raw data is stored in instances of the Buffer
class. A Buffer
is similarto an array of integers but corresponds to a raw memory allocation outsidethe V8 heap. ABuffer
cannot be resized.
在實例化的Buffer
類中存儲了原始數據。Buffer
類似于一個整數數組,但Buffer
對應了在V8堆(the V8 heap)外的原始存儲空間分配。一旦創建了Buffer
實例,則無法改變其大小。
The Buffer
object is global.
另外,Buffer
是一個全局對象。
Converting between Buffers and JavaScript string objects requires an explicit encodingmethod. Here are the different string encodings;
在緩沖器(Buffers)和JavaScript間進行字符串的轉換需要調用特定的編碼方法。如下列舉了不同的編碼方法:
-
'ascii'
- for 7 bit ASCII data only. This encoding method is very fast, and willstrip the high bit if set.
'ascii'
- 僅對應7位的ASCII數據。雖然這種編碼方式非常迅速,并且如果設置了最高位,則會將其移去。
-
'utf8'
- Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.
'utf8'
- 對應多字節編碼Unicode字符。大量網頁和其他文件格式使用這類編碼方式。
-
'ucs2'
- 2-bytes, little endian encoded Unicode characters. It can encodeonly BMP(Basic Multilingual Plane, U+0000 - U+FFFF).
'ucs2'
- 2字節的,低字節序編碼Unicode字符。只能編碼BMP(第零平面,U+0000 - U+FFFF)字符。
-
'base64'
- Base64 string encoding.
'base64'
- Base64 字符串編碼.
-
'binary'
- A way of encoding raw binary data into strings by using onlythe first 8 bits of each character. This encoding method is depreciated andshould be avoided in favor ofBuffer
objects where possible. This encodingwill be removed in future versions of Node.
'binary'
- 僅使用每個字符的頭8位將原始的二進制信息進行編碼。在需使用Buffer
的情況下,應該盡量避免使用這個已經過時的編碼方式。而且,這個編碼方式不會出現在未來版本的Node中。
-
'hex'
- Encode each byte as two hexidecimal characters.
'hex'
- 將一個字節編碼為兩個16進制字符。
new Buffer(size)
Allocates a new buffer of size
octets.
分配給一個新創建的buffer實例一個大小為size
字節的空間。
new Buffer(array)
Allocates a new buffer using an array
of octets.
使用array
的空間創建一個buffer實例。
new Buffer(str, encoding='utf8')
Allocates a new buffer containing the given str
.
創建一個包含給定str
的buffer實例。
buffer.write(string, offset=0, encoding='utf8')
Writes string
to the buffer at offset
using the given encoding. Returnsnumber of octets written. Ifbuffer
did not contain enough space to fitthe entire string, it will write a partial amount of the string. In the caseof'utf8'
encoding, the method will not write partial characters.
通過給定的編碼方式把string
寫入到buffer的offset
(偏移地址)中,并且返回寫入的字節數。如果當前的buffer
沒有足夠存儲空間,字符串會部分地保存在buffer
中,而不是整串字符。需要注意的是,如果使用'utf8'
進行編碼,該方法不會對零散的字符進行編寫。
Example: write a utf8 string into a buffer, then print it
例如:將一串utf8格式的字符串寫入Buffer,然后輸出:
buf = new Buffer(256);
len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(len + " bytes: " + buf.toString('utf8', 0, len));
buffer.toString(encoding, start=0, end=buffer.length)
Decodes and returns a string from buffer data encoded with encoding
beginning atstart
and ending at end
.
對緩沖器中的以encoding
方式編碼的,以start
標識符開始,以end
標識符結尾的緩沖數據進行解碼,并輸出字符串。
See buffer.write()
example, above.
參見上文的buffer.write()
例子。
buffer[index]
Get and set the octet at index
. The values refer to individual bytes,so the legal range is between0x00
and 0xFF
hex or 0
and 255
.
獲取或者設置位于index
字節的值。由于返回值為單個的字節,因此其范圍應該在0x00
到 0xFF
(16進制)或者0
and255
(10進制)之間
Example: copy an ASCII string into a buffer, one byte at a time:
例如:通過每次僅輸入一個字符的方式將整串ASCII字符錄入Buffer中:
str = "node.js";
buf = new Buffer(str.length);
for (var i = 0; i < str.length ; i++) {
buf[i] = str.charCodeAt(i);
}
console.log(buf);
Buffer.isBuffer(obj)
Tests if obj
is a Buffer
.
驗證obj
的類別是否為Buffer
類。
Buffer.byteLength(string, encoding='utf8')
Gives the actual byte length of a string. This is not the same asString.prototype.length
since that returns the number ofcharacters in astring.
返回字符串長度的實際值。與String.prototype.length
的區別之處在于該方法返回的是字符串中characters的個數。
Example:
例如:
str = '\u00bd + \u00bc = \u00be';
console.log(str + ": " + str.length + " characters, " +
Buffer.byteLength(str, 'utf8') + " bytes");
buffer.length
The size of the buffer in bytes. Note that this is not necessarily the sizeof the contents.length
refers to the amount of memory allocated for thebuffer object. It does not change when the contents of the buffer are changed.
返回Buffer占用的字節數。需要注意的是,length
并非其內容占的大小,而是指分配給Buffer實例的存儲空間的大小,因此該值不會隨Buffer內容的變化而變化。
buf = new Buffer(1234);
console.log(buf.length);
buf.write("some string", "ascii", 0);
console.log(buf.length);
buffer.copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Does a memcpy() between buffers.
在兩個Buffer之間進行memcpy() 操作。
Example: build two Buffers, then copy buf1
from byte 16 through byte 19intobuf2
, starting at the 8th byte in buf2
.
例如:創建2個Buffer實例,然后將buf1
中第16字節到第19字節間的信息復制到buf2
中,并使在buf2
中新的字符串首字符位于第8字節:
buf1 = new Buffer(26);
buf2 = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97;
buf2[i] = 33;
}
buf1.copy(buf2, 8, 16, 20);
console.log(buf2.toString('ascii', 0, 25));
buffer.slice(start, end=buffer.length)
Returns a new buffer which references thesame memory as the old, but offset and cropped by thestart
and end
indexes.
返回一個和原Buffer引用相同存儲空間的新Buffer,但是新Buffer中的偏移地址截取了原Buffer偏移地址中自start
到end
的部分。
Modifying the new buffer slice will modify memory in the original buffer!
特別注意:通過修改新的Buffer切片(slice)中的內容同樣會修改存儲在原Buffer中的信息!
Example: build a Buffer with the ASCII alphabet, take a slice, then modify one bytefrom the original Buffer.
例如:建立一個ASCII碼型的字母表,再建立一個切片,并在原Buffer中修改一個字節:
var buf1 = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97;
}
var buf2 = buf1.slice(0, 3);
console.log(buf2.toString('ascii', 0, buf2.length));
buf1[0] = 33;
console.log(buf2.toString('ascii', 0, buf2.length));
Streams 流
A stream is an abstract interface implemented by various objects in Node.For example a request to an HTTP server is a stream, as is stdout. Streamsare readable, writable, or both. All streams are instances ofEventEmitter
.
在Node中,Stream(流)是一個由不同對象實現的抽象接口。例如請求HTTP服務器的request是一個流,類似于stdout(標準輸出)。流可以是可讀的,可寫的,或者既可讀又可寫。所有流都是EventEmitter
的實例。
Readable Stream 可讀流
A Readable Stream
has the following methods, members, and events.
一個可讀流
具有下述的方法、成員、及事件。
Event: 'data' 事件:'data'
function (data) { }
The 'data'
event emits either a Buffer
(by default) or a string ifsetEncoding()
was used.
'data'
事件的回調函數參數默認情況下是一個Buffer
對象。如果使用了setEncoding()
則參數為一個字符串。
Event: 'end' 事件:'end'
function () { }
Emitted when the stream has received an EOF (FIN in TCP terminology).Indicates that no more'data'
events will happen. If the stream is alsowritable, it may be possible to continue writing.
當流中接收到EOF(TCP中為FIN)時此事件被觸發,表示流的讀取已經結束,不會再發生任何'data'
事件。如果流同時也是可寫的,那它還可以繼續寫入。
Event: 'error' 事件:'error'
function (exception) { }
Emitted if there was an error receiving data.
接收數據的過程中發生任何錯誤時,此事件被觸發。
Event: 'close' 事件:'close'
function () { }
Emitted when the underlying file descriptor has been closed. Not all streamswill emit this. (For example, an incoming HTTP request will not emit'close'
.)
當底層的文件描述符被關閉時觸發此事件,并不是所有流都會觸發這個事件。(例如,一個連接進入的HTTP request流就不會觸發'close'
事件。)
Event: 'fd' 事件:'fd'
function (fd) { }
Emitted when a file descriptor is received on the stream. Only UNIX streamssupport this functionality; all others will simply never emit this event.
當在流中接收到一個文件描述符時觸發此事件。只有UNIX流支持這個功能,其他類型的流均不會觸發此事件。
stream.readable
A boolean that is true
by default, but turns false
after an'error'
occurred, the stream came to an 'end'
, or destroy()
was called.
這是一個布爾值,默認值為true
。當'error'
事件或'end'
事件發生后,或者destroy()
被調用后,這個屬性將變為false
。
stream.setEncoding(encoding)
Makes the data event emit a string instead of a Buffer
. encoding
can be'utf8'
,'ascii'
, or 'base64'
.
調用此方法會影響'data'
事件的回調函數參數形式,默認為Buffer
對象,調用此方法后為字符串。encoding
參數可以是'utf8'
、'ascii'
、或'base64'
。
stream.pause()
Pauses the incoming 'data'
events.
暫停'data'
事件的觸發。
stream.resume()
Resumes the incoming 'data'
events after a pause()
.
恢復被pause()
調用暫停的'data'
事件觸發。
stream.destroy()
Closes the underlying file descriptor. Stream will not emit any more events.
關閉底層的文件描述符。流上將不會再觸發任何事件。
stream.destroySoon()
After the write queue is drained, close the file descriptor.
在寫隊列清空后(所有寫操作完成后),關閉文件描述符。
stream.pipe(destination, [options])
This is a Stream.prototype
method available on all Stream
s.
這是Stream.prototype
(Stream原型對象)的一個方法,對所有Stream
對象有效。
Connects this read stream to destination
WriteStream. Incomingdata on this stream gets written todestination
. The destination and sourcestreams are kept in sync by pausing and resuming as necessary.
用于將這個可讀流和destination
目標可寫流連接起來,傳入這個流中的數據將會寫入到destination
流中。通過在必要時暫停和恢復流,來源流和目的流得以保持同步。
Emulating the Unix cat
command:
模擬Unix系統的cat
命令:
process.stdin.resume();
process.stdin.pipe(process.stdout);
By default end()
is called on the destination when the source stream emitsend
, so thatdestination
is no longer writable. Pass { end: false }
asoptions
to keep the destination stream open.
默認情況下,當來源流的end
事件觸發時目的流的end()
方法會被調用,此時destination
目的流將不再可寫入。要在這種情況下為了保持目的流仍然可寫入,可將options
參數設為{ end: false }
。
This keeps process.stdout
open so that "Goodbye" can be written at the end.
這使process.stdout
保持打開狀態,因此"Goodbye"可以在end事件發生后被寫入。
process.stdin.resume();
process.stdin.pipe(process.stdout, { end: false });
process.stdin.on("end", function() {
process.stdout.write("Goodbye\n");
});
NOTE: If the source stream does not support pause()
and resume()
, this functionadds simple definitions which simply emit'pause'
and 'resume'
events onthe source stream.
注意:如果來源流不支持pause()
和resume()
方法,此函數將在來源流對象上增加這兩個方法的簡單定義,內容為觸發'pause'
和'resume'
事件。
Writable Stream 可寫流
A Writable Stream
has the following methods, members, and events.
一個可寫流
具有下列方法、成員、和事件。
Event: 'drain' 事件:'drain'
function () { }
Emitted after a write()
method was called that returned false
toindicate that it is safe to write again.
發生在write()
方法被調用并返回false
之后。此事件被觸發說明內核緩沖區已空,再次寫入是安全的。
Event: 'error' 事件:'error'
function (exception) { }
Emitted on error with the exception exception
.
發生錯誤時被觸發,回調函數接收一個異常參數exception
。
Event: 'close' 事件:'close'
function () { }
Emitted when the underlying file descriptor has been closed.
底層文件描述符被關閉時被觸發。
Event: 'pipe' 事件:'pipe'
function (src) { }
Emitted when the stream is passed to a readable stream's pipe method.
當此可寫流作為參數傳給一個可讀流的pipe方法時被觸發。
stream.writable
A boolean that is true
by default, but turns false
after an'error'
occurred or end()
/ destroy()
was called.
一個布爾值,默認值為true
。在'error'
事件被觸發之后,或end()
/destroy()
方法被調用后此屬性被設為false
。
stream.write(string, encoding='utf8', [fd])
Writes string
with the given encoding
to the stream. Returnstrue
ifthe string has been flushed to the kernel buffer. Returns false
toindicate that the kernel buffer is full, and the data will be sent out inthe future. The'drain'
event will indicate when the kernel buffer isempty again. Theencoding
defaults to 'utf8'
.
使用指定編碼encoding
將字符串string
寫入到流中。如果字符串被成功寫入內核緩沖區,此方法返回true
。如果內核緩沖區已滿,此方法返回false
,數據將在以后被送出。當內核緩沖區再次被清空后'drain'事件將被觸發。
encoding參數默認為
'utf8'`。
If the optional fd
parameter is specified, it is interpreted as an integralfile descriptor to be sent over the stream. This is only supported for UNIXstreams, and is silently ignored otherwise. When writing a file descriptor inthis manner, closing the descriptor before the stream drains risks sending aninvalid (closed) FD.
如果指定了可選參數fd
,它將被作為一個文件描述符通過流傳送。此功能僅被Unix流所支持,對于其他流此操作將被忽略而沒有任何提示。當使用此方法傳送一個文件描述符時,如果在流沒有清空前關閉此文件描述符,將造成傳送一個無效(已關閉)FD的風險。
stream.write(buffer)
Same as the above except with a raw buffer.
除了用一個Buffer對象替代字符串之外,其他同上。
stream.end()
Terminates the stream with EOF or FIN.
使用EOF或FIN結束一個流的輸出。
stream.end(string, encoding)
Sends string
with the given encoding
and terminates the stream with EOFor FIN. This is useful to reduce the number of packets sent.
以指定的字符編碼encoding
傳送一個字符串string
,然后使用EOF或FIN結束流的輸出。這對降低數據包傳輸量有所幫助。
stream.end(buffer)
Same as above but with a buffer
.
除了用一個buffer
對象替代字符串之外,其他同上。
stream.destroy()
Closes the underlying file descriptor. Stream will not emit any more events.
關閉底層文件描述符。在此流上將不會再觸發任何事件。
Crypto 加密模塊
Use require('crypto')
to access this module.
使用require('crypto')
調用加密模塊。
The crypto module requires OpenSSL to be available on the underlying platform.It offers a way of encapsulating secure credentials to be used as partof a secure HTTPS net or http connection.
加密模塊需要底層系統提供OpenSSL的支持。它提供了一種安全憑證的封裝方式,可以用于HTTPS安全網絡以及普通HTTP連接。
It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.
該模塊還提供了一套針對OpenSSL的hash(哈希),hmac(密鑰哈希),cipher(編碼),decipher(解碼),sign(簽名)以及verify(驗證)等方法的封裝。
crypto.createCredentials(details)
Creates a credentials object, with the optional details being a dictionary with keys:
創建一個憑證對象,可選參數details為一個帶鍵值的字典:
-
key
: a string holding the PEM encoded private key
key
:為字符串型,PEM編碼的私鑰。
-
cert
: a string holding the PEM encoded certificate
cert
:為字符串型,PEM編碼的認證證書。
-
ca
: either a string or list of strings of PEM encoded CA certificates to trust.
ca
:字符串形式的PEM編碼可信CA證書,或證書列表。
If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given inhttp://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.
如果沒有給出'ca'的詳細內容,那么node.js將會使用默認的公開受信任列表,該表位于http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt。
crypto.createHash(algorithm)
Creates and returns a hash object, a cryptographic hash with the given algorithmwhich can be used to generate hash digests.
創建并返回一個hash對象,它是一個指定算法的加密hash,用于生成hash摘要。
algorithm
is dependent on the available algorithms supported by the versionof 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.
參數algorithm
可選擇系統上安裝的OpenSSL版本所支持的算法。例如:'sha1'
, 'md5'
, 'sha256'
, 'sha512'
等。在近期發行的版本中,openssl list-message-digest-algorithms
會顯示這些可用的摘要算法。
hash.update(data)
Updates the hash content with the given data
.This can be called many times with new data as it is streamed.
更新hash的內容為指定的data
。當使用流數據時可能會多次調用該方法。
hash.digest(encoding='binary')
Calculates the digest of all of the passed data to be hashed.The encoding
can be'hex'
, 'binary'
or 'base64'
.
計算所有傳入數據的hash摘要。參數encoding
(編碼方式)可以為'hex'
, 'binary'
或者'base64'
。
crypto.createHmac(algorithm, key)
Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.
創建并返回一個hmac對象,它是一個指定算法和密鑰的加密hmac。
algorithm
is dependent on the available algorithms supported by OpenSSL - see createHash above.key
is the hmac key to be used.
參數algorithm
可選擇OpenSSL支持的算法 - 參見上文的createHash。參數key
為hmac所使用的密鑰。
hmac.update(data)
Update the hmac content with the given data
.This can be called many times with new data as it is streamed.
更新hmac的內容為指定的data
。當使用流數據時可能會多次調用該方法。
hmac.digest(encoding='binary')
Calculates the digest of all of the passed data to the hmac.The encoding
can be'hex'
, 'binary'
or 'base64'
.
計算所有傳入數據的hmac摘要。參數encoding
(編碼方式)可以為'hex'
, 'binary'
或者'base64'
。
crypto.createCipher(algorithm, key)
Creates and returns a cipher object, with the given algorithm and key.
使用指定的算法和密鑰創建并返回一個cipher對象。
algorithm
is dependent on OpenSSL, examples are 'aes192'
, etc.On recent releases,openssl list-cipher-algorithms
will display the available cipher algorithms.
參數algorithm
可選擇OpenSSL支持的算法,例如'aes192'
等。在最近的發行版中,openssl list-cipher-algorithms
會顯示可用的加密的算法。
cipher.update(data, input_encoding='binary', output_encoding='binary')
Updates the cipher with data
, the encoding of which is given in input_encoding
and can be 'utf8'
, 'ascii'
or 'binary'
. The output_encoding
specifiesthe output format of the enciphered data, and can be'binary'
, 'base64'
or 'hex'
.
使用參數data
更新要加密的內容,其編碼方式由參數input_encoding
指定,可以為 'utf8'
, 'ascii'
或者'binary'
。參數output_encoding
指定了已加密內容的輸出編碼方式,可以為'binary'
, 'base64'
或'hex'
。
Returns the enciphered contents, and can be called many times with new data as it is streamed.
返回已加密的內容,當使用流數據時可能會多次調用該方法。
cipher.final(output_encoding='binary')
Returns any remaining enciphered contents, with output_encoding
being one of:'binary'
, 'ascii'
or 'utf8'
.
返回所有剩余的加密內容,output_encoding
輸出編碼為'binary'
, 'ascii'
或'utf8'
其中之一。
crypto.createDecipher(algorithm, key)
Creates and returns a decipher object, with the given algorithm and key.This is the mirror of the cipher object above.
使用給定的算法和密鑰創建并返回一個解密對象。該對象為上述加密對象的反向運算。
decipher.update(data, input_encoding='binary', output_encoding='binary')
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'
.
使用參數data
更新要解密的內容,其編碼方式為'binary'
,'base64'
或'hex'
。參數output_encoding
指定了已解密的明文內容的輸出編碼方式,可以為'binary'
,'ascii'
或'utf8'
。
decipher.final(output_encoding='binary')
Returns any remaining plaintext which is deciphered,with output_encoding' being one of:
'binary',
'ascii' or
'utf8'`.
返回全部剩余的已解密的明文,其output_encoding' 為
'binary',
'ascii'或
'utf8'`其中之一。
crypto.createSign(algorithm)
Creates and returns a signing object, with the given algorithm.On recent OpenSSL releases,openssl list-public-key-algorithms
will displaythe available signing algorithms. Examples are'RSA-SHA256'
.
使用給定的算法創建并返回一個簽名器對象。在現有的OpenSSL發行版中,openssl list-public-key-algorithms
會顯示可用的簽名算法,例如:'RSA-SHA256'
。
signer.update(data)
Updates the signer object with data.This can be called many times with new data as it is streamed.
使用data參數更新簽名器對象。當使用流數據時可能會多次調用該方法。
signer.sign(private_key, output_format='binary')
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.
對所有傳入簽名器的數據計算其簽名。private_key
為字符串,它包含了PEM編碼的用于簽名的私鑰。
Returns the signature in output_format
which can be 'binary'
,'hex'
or 'base64'
.
返回簽名,其output_format
輸出可以為'binary'
, 'hex'
或者'base64'
。
crypto.createVerify(algorithm)
Creates and returns a verification object, with the given algorithm.This is the mirror of the signing object above.
使用給定算法創建并返回一個驗證器對象。它是上述簽名器對象的反向運算。
verifier.update(data)
Updates the verifier object with data.This can be called many times with new data as it is streamed.
使用data參數更新驗證器對象。當使用流數據時可能會多次調用該方法。
verifier.verify(cert, signature, signature_format='binary')
Verifies the signed data by using the cert
which is a string containingthe PEM encoded public key, andsignature
, which is the previously calculatessignature for the data, in thesignature_format
which can be 'binary'
, 'hex'
or'base64'
.
使用參數cert
和signature
驗證已簽名的數據,cert
為經過PEM編碼的公鑰字符串,signature
為之前已計算的數據的簽名,signature_format
可以為'binary'
,'hex'
或者'base64'
。
Returns true or false depending on the validity of the signature for the data and public key.
根據對數據和公鑰進行簽名有效性驗證的結果,返回true或者false。## TLS (SSL) TLS (SSL)模塊
Use require('tls')
to access this module.
使用require('tls')
訪問此模塊。
The tls
module uses OpenSSL to provide Transport Layer Security and/orSecure Socket Layer: encrypted stream communication.
tls
模塊使用OpenSSL提供Transport Layer Security(傳輸層安全協議)和 / 或Secure Socket Layer(安全套接層協議):加密的通信流。
TLS/SSL is a public/private key infrastructure. Each client and eachserver must have a private key. A private key is created like this
TLS/SSL基于公鑰/私鑰的非對稱加密體系,每一個客戶端與服務器都需要擁有一個私有密鑰。私有密鑰可用如下方式生成:
openssl genrsa -out ryans-key.pem 1024
All severs and some clients need to have a certificate. Certificates are publickeys signed by a Certificate Authority or self-signed. The first step togetting a certificate is to create a "Certificate Signing Request" (CSR)file. This is done with:
所有服務器和一部分客戶端需要擁有一份數字證書。數字證書是由某個CA(數字證書認證機構)使用其公鑰簽名授予的,或者也可以用戶自簽名。要獲得一份數字證書,首先需要生成一個CSR(證書簽名請求)文件。方法如下:
openssl req -new -key ryans-key.pem -out ryans-csr.pem
To create a self-signed certificate with the CSR, do this:
要使用CSR文件生成一個自簽名的數字證書,方法如下:
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.
你也可以將CSR文件發給一家CA以獲得簽名。
(TODO: docs on creating a CA, for now interested users should just look attest/fixtures/keys/Makefile
in the Node source code)
(關于如何創建CA的文檔有待補充。感興趣的用戶可以直接瀏覽Node源代碼中的test/fixtures/keys/Makefile
文件)
s = tls.connect(port, [host], [options], callback)
Creates a new client connection to the given port
and host
. (Ifhost
defaults to localhost
.) options
should be an object which specifies
建立一個到指定端口port
和主機host
的新的客戶端連接。(host
參數的默認值為localhost
。)options
是一個包含以下內容的對象:
-
key
: A string or Buffer
containing the private key of the server inPEM format. (Required)
key
:包含服務器私鑰的字符串或Buffer
對象。密鑰的格式為PEM。(必選)
-
cert
: A string or Buffer
containing the certificate key of the server inPEM format.
cert
:包含服務器數字證書密鑰的字符串或Buffer
對象。密鑰的格式為PEM。
-
ca
: An array of strings or Buffer
s of trusted certificates. If this isomitted several well known "root" CAs will be used, like VeriSign.These are used to authorize connections.
ca
:包含可信任數字證書字符串或Buffer
對象的數組。如果忽略此屬性,則會使用幾個常見的"根"CA的數字證書,如VeriSign。這些數字證書將被用來對連接進行驗證。
tls.connect()
returns a cleartext CryptoStream
object.
tls.connect()
返回一個明文的CryptoStream
對象。
After the TLS/SSL handshake the callback
is called. The callback
will becalled no matter if the server's certificate was authorized or not. It is upto the user to tests.authorized
to see if the server certificate wassigned by one of the specified CAs. Ifs.authorized === false
then the errorcan be found in s.authorizationError
.
TLS/SSL連接握手之后callback
回調函數會被調用。無論服務器的數字證書是否通過驗證,callback
函數都會被調用。用戶應該檢查s.authorized
以確定服務器數字證書是否通過了驗證(被某個可信任的CA簽名)。當s.authorized === false
時可以從s.authorizationError
中獲得具體的錯誤。
tls.Server
This class is a subclass of net.Server
and has the same methods on it.Instead of accepting just raw TCP connections, this accepts encryptedconnections using TLS or SSL.
這是net.Server
的子類,擁有和net.Server
完全一樣的方法。區別在于這個類使用TLS或SSL建立加密的連接,而非僅僅接受原始的TCP連接。
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
連接到這個服務器進行測試:
openssl s_client -connect 127.0.0.1:8000
tls.createServer(options, secureConnectionListener)
This is a constructor for the tls.Server
class. The options objecthas these possibilities:
這是tls.Server
類的構造函數。參數options對象可以包含下列內容:
-
key
: A string or Buffer
containing the private key of the server inPEM format. (Required)
key
:包含服務器私鑰的字符串或Buffer
對象。密鑰的格式為PEM。(必選)
-
cert
: A string or Buffer
containing the certificate key of the server inPEM format. (Required)
cert
:包含服務器數字證書密鑰的字符串或Buffer
對象。密鑰的格式為PEM。(必選)
-
ca
: An array of strings or Buffer
s of trusted certificates. If this isomitted several well known "root" CAs will be used, like VeriSign.These are used to authorize connections.
ca
:包含可信任數字證書字符串或Buffer
對象的數組。如果忽略此屬性,則會使用幾個常見的"根"CA的數字證書,如VeriSign。這些證書將被用來對連接進行驗證。
-
requestCert
: If true
the server will request a certificate fromclients that connect and attempt to verify that certificate. Default:false
.
requestCert
:如果設為true
則服務器會向建立連接的客戶端要求一個數字證書,并且試圖去驗證這份數字證書。默認為false
。
-
rejectUnauthorized
: If true
the server will reject any connectionwhich is not authorized with the list of supplied CAs. This option onlyhas an effect ifrequestCert
is true
. Default: false
.
rejectUnauthorized
:如果設為true
則服務器將拒絕任何沒有通過CA驗證的連接。此選項僅在requestCert
設為true
時有效。默認為false
。
Event: 'secureConnection' 事件:'secureConnection'
function (cleartextStream) {}
This event is emitted after a new connection has been successfullyhandshaked. The argument is a duplex instance ofstream.Stream
. It has allthe common stream methods and events.
當一個新的連接成功完成握手過程后此事件被觸發。參數是一個可讀可寫的stream.Stream
實例對象,此對象具有Stream(流)對象所有公共的方法和事件。
cleartextStream.authorized
is a boolean value which indicates if theclient has verified by one of the supplied certificate authorities for theserver. IfcleartextStream.authorized
is false, thencleartextStream.authorizationError
is set to describe how authorizationfailed. Implied but worth mentioning: depending on the settings of the TLSserver, you unauthorized connections may be accepted.
cleartextStream.authorized
是一個布爾值,用以表明客戶端是否通過了服務器所指定的可信任CA的驗證。如果cleartextStream.authorized
值為false,則可以從cleartextStream.authorizationError
中獲得驗證失敗的原因。這意味著:未經驗證的連接是有可能被接受的,這依賴于TLS服務器的具體設置。
server.listen(port, [host], [callback])
Begin accepting connections on the specified port
and host
. If thehost
is omitted, the server will accept connections directed to anyIPv4 address (INADDR_ANY
).
開始在指定的端口port
和主機名host
上接受連接。如果沒有設置host
參數,服務器將接受到達本機所有IPv4地址(INADDR_ANY
)的連接。
This function is asynchronous. The last parameter callback
will be calledwhen the server has been bound.
此函數是異步的。最后一個參數callback
所指定的回調函數會在服務器綁定完成后被調用。
See net.Server
for more information.
更多信息參見net.Server
。
server.close()
Stops the server from accepting new connections. This function isasynchronous, the server is finally closed when the server emits a'close'
event.
關閉服務器,停止接受新的連接請求。此函數是異步的,當服務器觸發一個'close'
事件時才真正被關閉。
server.maxConnections
Set this property to reject connections when the server's connection count gets high.
服務器最大連接數量。服務器會拒絕超過此數量限制的連接,以防止同時建立的連接數過多。
server.connections
The number of concurrent connections on the server.
服務器并發連接數量。
File System 文件系統模塊
File I/O is provided by simple wrappers around standard POSIX functions. Touse this module dorequire('fs')
. All the methods have asynchronous andsynchronous forms.
文件的I/O是由標準POSIX函數封裝而成。需要使用require('fs')
訪問這個模塊。所有的方法都提供了異步和同步兩種方式。
The asynchronous form always take a completion callback as its last argument.The arguments passed to the completion callback depend on the method, but thefirst argument is always reserved for an exception. If the operation wascompleted successfully, then the first argument will be null
or undefined
.
異步形式下,方法的最后一個參數需要傳入一個執行完成時的回調函數。傳給回調函數的參數取決于具體的異步方法,但第一個參數總是保留給異常對象。如果操作成功,那么該異常對象就變為null
或者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 thefollowing 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.stat
在fs.rename
之前執行,正確的做法是鏈式調用回調函數。
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 theasynchronous versions of these calls. The synchronous versions will blockthe entire process until they complete--halting all connections.
當需要頻繁操作時,強烈建議使用異步方法。同步方式在其完成之前將會阻塞當前的整個進程,即擱置所有連接。
fs.rename(path1, path2, [callback])
Asynchronous rename(2). No arguments other than a possible exception are givento the completion callback.
異步調用rename(2),重命名某個文件,除非回調函數執行過程出現了異常,否則不會傳遞任何參數。
fs.renameSync(path1, path2)
Synchronous rename(2).
同步調用重命名rename(2),重命名某個文件。
fs.truncate(fd, len, [callback])
Asynchronous ftruncate(2). No arguments other than a possible exception aregiven to the completion callback.
異步調用ftruncate(2),截斷某個文件,除非回調函數執行過程出現了異常,否則不會傳遞任何參數。
fs.truncateSync(fd, len)
Synchronous ftruncate(2).
同步調用重命名ftruncate(2),截斷某個文件s。
fs.chmod(path, mode, [callback])
Asynchronous chmod(2). No arguments other than a possible exception are givento the completion callback.
異步調用chmod(2),修改文件權限,除非回調函數執行過程出現了異常,否則不會傳遞任何參數。
fs.chmodSync(path, mode)
Synchronous chmod(2).
同步調用chmod(2),修改文件權限。
fs.stat(path, [callback])
Asynchronous stat(2). The callback gets two arguments (err, stats)
wherestats
is afs.Stats
object. It looks like this:
異步調用stat(2),讀取文件元信息,回調函數將返回兩個參數(err, stats)
,其中stats
是fs.Stats
的一個對象,如下所示:
{ 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.
有關詳細信息,請參閱下面的fs.Stats
部分
fs.lstat(path, [callback])
Asynchronous lstat(2). The callback gets two arguments (err, stats)
wherestats
is afs.Stats
object. lstat() is identical to stat(), except that ifpath is a symbolic link, then the link itself is stat-ed, not the file that itrefers to.
異步形式調用lstat(2),回調函數返回兩個參數(err, stats)
,其中stats
是fs.Stats
的一個對象,lstat()和stat()類似,區別在于當path是一個符號鏈接時,它指向該鏈接的屬性,而不是所指向文件的屬性.
fs.fstat(fd, [callback])
Asynchronous fstat(2). The callback gets two arguments (err, stats)
wherestats
is afs.Stats
object.
異步形式調用fstat(2),回調函數返回兩個參數(err, stats)
,其中stats
是fs.Stats
的一個對象。
fs.statSync(path)
Synchronous stat(2). Returns an instance of fs.Stats
.
同步形式調用stat(2),返回fs.Stats
的一個實例。
fs.lstatSync(path)
Synchronous lstat(2). Returns an instance of fs.Stats
.
同步形式調用lstat(2),返回fs.Stats
的一個實例。
fs.fstatSync(fd)
Synchronous fstat(2). Returns an instance of fs.Stats
.
同步形式調用fstatSync(2),返回fs.Stats
的一個實例。
fs.link(srcpath, dstpath, [callback])
Asynchronous link(2). No arguments other than a possible exception are given tothe completion callback.
異步調用link(2),創建符號連接,除非回調函數執行過程出現了異常,否則不會傳遞任何參數。
fs.linkSync(srcpath, dstpath)
Synchronous link(2).
同步調用link(2)。
fs.symlink(linkdata, path, [callback])
Asynchronous symlink(2). No arguments other than a possible exception are givento the completion callback.
異步調用symlink(2),除非回調函數執行過程出現了異常,否則不會傳遞任何參數。
fs.symlinkSync(linkdata, path)
Synchronous symlink(2).
同步調用symlink(2)。
fs.readlink(path, [callback])
Asynchronous readlink(2). The callback gets two arguments (err,resolvedPath)
.
異步調用readlink,回調函數返回兩個參數(err,resolvedPath)
,resolvedPath
為解析后的文件路徑。
fs.readlinkSync(path)
Synchronous readlink(2). Returns the resolved path.
同步調用readlink(2),返回解析后的文件路徑。
fs.realpath(path, [callback])
Asynchronous realpath(2). The callback gets two arguments (err,resolvedPath)
.
異步調用realpath(2),回調函數返回兩個參數(err,resolvedPath)
,resolvedPath為解析后的文件路徑。
fs.realpathSync(path)
Synchronous realpath(2). Returns the resolved path.
同步調用realpath(2),返回解析后的文件路徑。
fs.unlink(path, [callback])
Asynchronous unlink(2). No arguments other than a possible exception are givento the completion callback.
異步調用unlink(2),刪除鏈接或者文件,除非回調函數執行過程出現了異常,否則不會傳遞任何參數。
fs.unlinkSync(path)
Synchronous unlink(2).
同步調用unlink(2)。
fs.rmdir(path, [callback])
Asynchronous rmdir(2). No arguments other than a possible exception are givento the completion callback.
異步調用rmdir(2),除非回調函數執行過程出現了異常,否則不會傳遞任何參數。
fs.rmdirSync(path)
Synchronous rmdir(2).
同步調用rmdir(2)。
fs.mkdir(path, mode, [callback])
Asynchronous mkdir(2). No arguments other than a possible exception are givento the completion callback.
異步調用mkdir(2),除非回調函數執行過程出現了異常,否則不會傳遞任何參數。
fs.mkdirSync(path, mode)
Synchronous mkdir(2).
同步調用mkdir(2)。
fs.readdir(path, [callback])
Asynchronous readdir(3). Reads the contents of a directory.The callback gets two arguments(err, files)
where files
is an array ofthe names of the files in the directory excluding'.'
and '..'
.
異步調用readdir(3),讀取目錄中的內容。回調函數接受兩個參數(err, files)
,其中files
參數是保存了目錄中所有文件名的數組('.'
和'..'
除外)。
fs.readdirSync(path)
Synchronous readdir(3). Returns an array of filenames excluding '.'
and'..'
.
同步調用readdir(3)。返回目錄中文件名數組('.'
與'..'
除外)。
fs.close(fd, [callback])
Asynchronous close(2). No arguments other than a possible exception are givento the completion callback.
異步同步調用close(2),關閉文件,除非回調函數執行過程出現了異常,否則不會傳遞任何參數。
fs.closeSync(fd)
Synchronous close(2).
同步調用close(2)。
fs.open(path, flags, mode=0666, [callback])
Asynchronous file open. See open(2). Flags can be 'r', 'r+', 'w', 'w+', 'a',or 'a+'. The callback gets two arguments(err, fd)
.
異步開啟文件,詳閱open(2)。標簽可為'r', 'r+', 'w', 'w+', 'a', 或 'a+'。回調函數接受兩個參數(err, fd)
。
fs.openSync(path, flags, mode=0666)
Synchronous open(2).
同步調用open(2)。
fs.utimes(path, atime, mtime, callback)
fs.utimesSync(path, atime, mtime)
Change file timestamps.
更改文件時間戳。
fs.futimes(path, atime, mtime, callback)
fs.futimesSync(path, atime, mtime)
Change file timestamps with the difference that if filename refers to asymbolic link, then the link is not dereferenced.
另一種更改文件時間戳的方式。區別在于如果文件名指向一個符號鏈接,則改變此符號鏈接的時間戳,而不改變所引用文件的時間戳。
fs.write(fd, buffer, offset, length, position, [callback])
Write buffer
to the file specified by fd
.
將buffer
緩沖器內容寫入fd
文件描述符。
offset
and length
determine the part of the buffer to be written.
offset
和length
決定了將緩沖器中的哪部分寫入文件。
position
refers to the offset from the beginning of the file where this datashould be written. Ifposition
is null
, the data will be written at thecurrent position.See pwrite(2).
position
指明將數據寫入文件從頭部算起的偏移位置,若position
為null
,數據將從當前位置開始寫入,詳閱pwrite(2)。
The callback will be given two arguments (err, written)
where written
specifies how many bytes were written.
回調函數接受兩個參數(err, written)
,其中written
標識有多少字節的數據已經寫入。
fs.writeSync(fd, buffer, offset, length, position)
Synchronous version of buffer-based fs.write()
. Returns the number of byteswritten.
基于緩沖器的fs.write()
的同步版本,返回寫入數據的字節數。
fs.writeSync(fd, str, position, encoding='utf8')
Synchronous version of string-based fs.write()
. Returns the number of byteswritten.
基于字符串的fs.write()
的同步版本,返回寫入數據的字節數。
fs.read(fd, buffer, offset, length, position, [callback])
Read data from the file specified by fd
.
從fd
文件描述符中讀取數據。
buffer
is the buffer that the data will be written to.
buffer
為寫入數據的緩沖器。
offset
is offset within the buffer where writing will start.
offset
為寫入到緩沖器的偏移地址。
length
is an integer specifying the number of bytes to read.
length
指明了欲讀取的數據字節數。
position
is an integer specifying where to begin reading from in the file.Ifposition
is null
, data will be read from the current file position.
position
為一個整形變量,標識從哪個位置開始讀取文件,如果position
參數為null
,數據將從文件當前位置開始讀取。
The callback is given the two arguments, (err, bytesRead)
.
回調函數接受兩個參數,(err, bytesRead)
。
fs.readSync(fd, buffer, offset, length, position)
Synchronous version of buffer-based fs.read
. Returns the number ofbytesRead
.
基于緩沖器的fs.read
的同步版本,返回讀取到的bytesRead
字節數。
fs.readSync(fd, length, position, encoding)
Synchronous version of string-based fs.read
. Returns the number ofbytesRead
.
基于字符串的fs.read
的同步版本,返回已經讀入的數據的字節數。
fs.readFile(filename, [encoding], [callback])
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 thecontents of the file.
回調函數將傳入兩個參數(err, data)
,其中data
為文件內容。
If no encoding is specified, then the raw buffer is returned.
如果沒有設置編碼,那么將返回原始內容格式的緩沖器。
fs.readFileSync(filename, [encoding])
Synchronous version of fs.readFile
. Returns the contents of the filename
.
同步調用fs.readFile
的版本,返回指定文件filename
的文件內容。
If encoding
is specified then this function returns a string. Otherwise itreturns a buffer.
如果設置了encoding
參數,將返回一個字符串。否則返回一個緩沖器。
fs.writeFile(filename, data, encoding='utf8', [callback])
Asynchronously writes data to a file. data
can be a string or a buffer.
異步寫入數據到某個文件中,data
可以是字符串或者緩沖器。
Example:
例子:
fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
fs.writeFileSync(filename, data, encoding='utf8')
The synchronous version of fs.writeFile
.
同步調用fs.writeFile
的方式。
fs.watchFile(filename, [options], listener)
Watch for changes on filename
. The callback listener
will be called eachtime the file is accessed.
監聽指定文件filename
的變化,回調函數listener
將在每次該文件被訪問時被調用。
The second argument is optional. The options
if provided should be an objectcontaining two members a boolean,persistent
, and interval
, a pollingvalue in milliseconds. The default is{ persistent: true, interval: 0 }
.
第二個參數是可選項,如果指定了options
參數,它應該是一個包含如下內容的對象:名為persistent
的布爾值,和名為interval
單位為毫秒的輪詢時間間隔,默認值為{ persistent: true, interval: 0 }
。
The listener
gets two arguments the current stat object and the previousstat object:
listener
監聽器將獲得兩個參數,分別標識當前的狀態對象和改變前的狀態對象。
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
.
這些狀態對象為fs.Stat
的實例。
If you want to be notified when the file was modified, not just accessedyou need to comparecurr.mtime
and `prev.mtime.
如果你想在文件被修改而不是被訪問時得到通知,你還需要比較curr.mtime
和prev.mtime
的值。
fs.unwatchFile(filename)
Stop watching for changes on filename
.
停止監聽文件filename
的變化。
fs.Stats
Objects returned from fs.stat()
and fs.lstat()
are of this type.
fs.stat()
和 fs.lstat()
方法返回的對象為此類型。
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink()
(only valid with fs.lstat()
)stats.isSymbolicLink()
(僅對fs.lstat()
有效)stats.isFIFO()
stats.isSocket()
fs.ReadStream
ReadStream
is a Readable Stream
.
ReadStream
是一個Readable Stream
可讀流。
fs.createReadStream(path, [options])
Returns a new ReadStream object (See Readable Stream
).
返回一個新的可讀流對象(參見Readable Stream
)。
options
is an object with the following defaults:
options
是包含如下默認值的對象:
{ flags: 'r',
encoding: null,
fd: null,
mode: 0666,
bufferSize: 64 * 1024
}
options
can include start
and end
values to read a range of bytes fromthe file instead of the entire file. Bothstart
and end
are inclusive andstart at 0. When used, both the limits must be specified always.
如果不想讀取文件的全部內容,可以在options
參數中設置start
和end
屬性值以讀取文件中指定范圍的內容。start
和end
包含在范圍中(閉集合),取值從0開始。這兩個參數需要同時設置。
An example to read the last 10 bytes of a file which is 100 bytes long:
一個例子演示了從一個長度為100字節的文件中讀取最后10個字節:
fs.createReadStream('sample.txt', {start: 90, end: 99});
fs.WriteStream
WriteStream
is a Writable Stream
.
WriteStream
為可寫流。
Event: 'open' 事件:'open'
function (fd) { }
fd
is the file descriptor used by the WriteStream.
fd
是可寫流所使用的文件描述符。
fs.createWriteStream(path, [options])
Returns a new WriteStream object (See Writable Stream
).
返回一個新的可寫流對象(參見Writable Stream
)。
options
is an object with the following defaults:
options
參數是包含如下默認值的對象:
{ flags: 'w',
encoding: null,
mode: 0666 }
Path 路徑模塊
This module contains utilities for dealing with file paths. Userequire('path')
to use it. It provides the following methods:
該模塊包括了一些處理文件路徑的功能,可以通過require('path')
方法來使用它。該模塊提供了如下的方法:
path.normalize(p)
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.
當發現有多個斜杠(/)時,系統會將他們替換為一個斜杠;如果路徑末尾中包含有一個斜杠,那么系統會保留這個斜杠。在Windows中,上述路徑中的斜杠(/)要換成反斜杠(\)。
Example:
示例:
path.normalize('/foo/bar//baz/asdf/quux/..')
'/foo/bar/baz/asdf'
path.join([path1], [path2], [...])
Join all arguments together and normalize the resulting path.
該方法用于合并方法中的各參數并得到一個標準化合并的路徑字符串。
Example:
示例:
node> require('path').join(
... '/foo', 'bar', 'baz/asdf', 'quux', '..')
'/foo/bar/baz/asdf'
path.resolve([from ...], to)
Resolves to
to an absolute path.
將to
參數解析為絕對路徑。
If to
isn't already absolute from
arguments are prepended in right to leftorder, until an absolute path is found. If after using allfrom
paths stillno absolute path is found, the current working directory is used as well. Theresulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.
如果參數 to
當前不是絕對的,系統會將from
參數按從右到左的順序依次前綴到to
上,直到在from
中找到一個絕對路徑時停止。如果遍歷所有from
中的路徑后,系統依然沒有找到一個絕對路徑,那么當前工作目錄也會作為參數使用。最終得到的路徑是標準化的字符串,并且標準化時系統會自動刪除路徑末尾的斜杠,但是如果獲取的路徑是解析到根目錄的,那么系統將保留路徑末尾的斜杠。
Another way to think of it is as a sequence of cd
commands in a shell.
你也可以將這個方法理解為Shell中的一組cd
命令。
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 befiles.
該方法與cd
命令的區別在于該方法中不同的路徑不一定存在,而且這些路徑也可能是文件。
Examples:
示例:
path.resolve('/foo/bar', './baz')
'/foo/bar/baz'
path.resolve('/foo/bar', '/tmp/file/')
'/tmp/file'
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
'/home/myself/node/wwwroot/static_files/gif/image.gif'
path.dirname(p)
Return the directory name of a path. Similar to the Unix dirname
command.
該方法返回一個路徑的目錄名,類似于Unix中的dirname
命令。
Example:
示例:
path.dirname('/foo/bar/baz/asdf/quux')
'/foo/bar/baz/asdf'
path.basename(p, [ext])
Return the last portion of a path. Similar to the Unix basename
command.
該方法返回一個路徑中最低一級目錄名,類似于Unix中的 basename
命令。
Example:
示例:
path.basename('/foo/bar/baz/asdf/quux.html')
'quux.html'
path.basename('/foo/bar/baz/asdf/quux.html', '.html')
'quux'
path.extname(p)
Return the extension of the path. Everything after the last '.' in the last portionof the path. If there is no '.' in the last portion of the path or the only '.' isthe first character, then it returns an empty string.
該方法返回路徑中的文件擴展名,即路徑最低一級的目錄中'.'字符后的任何字符串。如果路徑最低一級的目錄中'沒有'.' 或者只有'.',那么該方法返回一個空字符串。
Examples:
示例:
path.extname('index.html')
'.html'
path.extname('index')
''
path.exists(p, [callback])
Test whether or not the given path exists. Then, call the callback
argumentwith either true or false. Example:
該方法用于測試參數p
中的路徑是否存在。然后以true或者false作為參數調用callback
回調函數。示例:
path.exists('/etc/passwd', function (exists) {
util.debug(exists ? "it's there" : "no passwd!");
});
path.existsSync(p)
Synchronous version of path.exists
.
path.exists
的同步版本。## net 網絡模塊
The net
module provides you with an asynchronous network wrapper. It containsmethods for creating both servers and clients (called streams). You can includethis module withrequire("net");
net
模塊為你提供了一種異步網絡包裝器,它包含創建服務器和客戶端(稱為streams)所需的方法,您可以通過調用require("net")
來使用此模塊。
net.createServer([options], [connectionListener])
Creates a new TCP server. The connectionListener
argument isautomatically set as a listener for the'connection'
event.
創建一個新的TCP服務器,參數connectionListener
被自動設置為connection事件的監聽器。
options
is an object with the following defaults:
options
參數為一個對象,默認值如下: { allowHalfOpen: false }
If allowHalfOpen
is true
, then the socket won't automatically send FINpacket when the other end of the socket sends a FIN packet. The socket becomesnon-readable, but still writable. You should call the end() method explicitly.See'end'
event for more information.
如果allowHalfOpen
參數為true
,則當客戶端socket發送FIN包時,服務器端socket不會自動發送FIN包。此情況下服務器端socket將變為不可讀狀態,但仍然可寫。你需要明確的調用end()方法來關閉連接。更多內容請參照'end'
事件。
net.createConnection(arguments...)
Construct a new socket object and opens a socket to the given location. Whenthe socket is established the'connect'
event will be emitted.
創建一個新的socket對象,并建立到指定地址的socket連接。當socket建立后,'connect'
事件將被觸發。
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.
創建一個到主機host
的port
端口的TCP連接,如果略了host
參數,默認連接到localhost
。
-
net.createConnection(path)
Creates unix socket connection to path
創建連接到path
路徑的unix socket。
net.Server
This class is used to create a TCP or UNIX server.
這個類用于創建一個TCP或UNIX服務器。
Here is an example of a echo server which listens for connectionson port 8124:
下面的例子創建了一個在8124端口監聽的echo
服務器。
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
測試該服務器。
telnet localhost 8124
To listen on the socket /tmp/echo.sock
the last line would just bechanged to
如要監聽socket /tmp/echo.sock
,最后一行代碼需要修改成:
server.listen('/tmp/echo.sock');
Use nc
to connect to a UNIX domain socket server:
使用nc
命令連接到一個UNIX域socket服務器:
nc -U /tmp/echo.sock
net.Server
is an EventEmitter
with the following events:
net.Server
是下列事件的 EventEmitter
(事件觸發器):
server.listen(port, [host], [callback])
Begin accepting connections on the specified port
and host
. If thehost
is omitted, the server will accept connections directed to anyIPv4 address (INADDR_ANY
).
開始接收特定主機host
的port
端口的連接,如果省略了host
參數,服務器將接收任何指向IPV4地址的連接。
This function is asynchronous. The last parameter callback
will be calledwhen the server has been bound.
此函數是異步的,在服務器被綁定時,最后一個參數callback
回調函數將被調用。
One issue some users run into is getting EADDRINUSE
errors. Meaninganother server is already running on the requested port. One way of handling thiswould be to wait a second and the try again. This can be done with
一些用戶可能會遇到EADDRINUSE
錯誤,該錯誤消息的意思是已經有另一個服務運行在請求的端口上,一個解決方法就是等一會再試一下,就像下面的代碼這樣:
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)
(注意:Node中所有的socket都已經設置成SO_REUSEADDR端口重用模式)
server.listen(path, [callback])
Start a UNIX socket server listening for connections on the given path
.
啟動一個UNIX socket服務,監聽指定的path
路徑上的連接。
This function is asynchronous. The last parameter callback
will be calledwhen the server has been bound.
此函數是異步的,在服務器被綁定時,最后一個參數callback
回調函數將被調用。
server.listenFD(fd)
Start a server listening for connections on the given file descriptor.
啟動一個服務,監聽指定的文件描述符上的連接。
This file descriptor must have already had the bind(2)
and listen(2)
systemcalls invoked on it.
此文件描述符上必須已經執行了 bind(2)
和listen(2)
系統調用。
server.close()
Stops the server from accepting new connections. This function isasynchronous, the server is finally closed when the server emits a'close'
event.
關閉服務,停止接收新的連接。該函數是異步的,當服務發出'close'
事件時該服務器被最終關閉。
server.address()
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");
});
server.listen(function() {
address = server.address();
console.log("opened server on %j", address);
});
server.maxConnections
Set this property to reject connections when the server's connection count gets high.
設置該屬性的值,以便當服務器達到最大連接數時不再接受新的連接。
server.connections
The number of concurrent connections on the server.
服務器的并發連接數。
Event: 'connection' 事件:'connection'
function (socket) {}
Emitted when a new connection is made. socket
is an instance ofnet.Socket
.
當一個新的連接建立時觸發。socket
是net.Socket
的一個實例。
Event: 'close'
function () {}
Emitted when the server closes.
當服務器關閉時觸發。
net.Socket
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 theuser and used as a client (withconnect()
) or they can be created by Nodeand passed to the user through the'connection'
event of a server.
這是TCP或UNIX socket的抽象對象。net.Socket
實例實現了一個全雙工的流接口。此實例可以是由用戶建立用作客戶端(使用connect()
方法),也可能由Node建立并通過服務器的'connection'
事件傳給用戶。
net.Socket
instances are EventEmitters with the following events:
net.Socket
的實例是下列事件的事件觸發器:
new net.Socket([options])
Construct a new socket object.
構造一個新的socket對象。
options
is an object with the following defaults:
options
參數是一個對象,默認值如下:
{ fd: null
type: null
allowHalfOpen: false
}<
posted on 2012-08-30 12:31
王海光 閱讀(12926)
評論(0) 編輯 收藏 引用 所屬分類:
NodeJS