Node.js Manual & Documentation
Table Of Contents- Synopsis 概要
- Global Objects 全局對象
- Timers 定時器
- Modules 模塊
- Addenda: Package Manager Tips 附錄:包管理技巧
- Addons 擴展插件
- process 進程
- Event: 'exit' 事件:'exit'
- Event: 'uncaughtException' 事件:'uncaughtException'
- Signal Events 信號事件
- process.stdout
- process.stderr
- process.stdin
- process.argv
- process.execPath
- process.chdir(directory)
- process.cwd()
- process.env
- process.exit(code=0)
- process.getgid()
- process.setgid(id)
- process.getuid()
- process.setuid(id)
- process.version
- process.installPrefix
- process.kill(pid, signal='SIGTERM')
- process.pid
- process.title
- process.platform
- process.memoryUsage()
- process.nextTick(callback)
- process.umask([mask])
- 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)
- hash.digest(encoding='binary')
- crypto.createHmac(algorithm, key)
- hmac.update(data)
- hmac.digest(encoding='binary')
- crypto.createCipher(algorithm, key)
- cipher.update(data, input_encoding='binary', output_encoding='binary')
- cipher.final(output_encoding='binary')
- crypto.createDecipher(algorithm, key)
- decipher.update(data, input_encoding='binary', output_encoding='binary')
- decipher.final(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
- Event: 'connect' 事件:'connect'
- Event: 'data' 事件:'data'
- Event: 'end' 事件:'end'
- Event: 'timeout' 事件:'timeout'
- Event: 'drain' 事件:'drain'
- Event: 'error' 事件:'error'
- Event: 'close' 事件:'close'
- net.isIP
- DNS DNS模塊
- UDP / Datagram Sockets 數據報套接字模塊
- Event: 'message' 事件:'message'
- Event: 'listening' 事件:'listening'
- Event: 'close' 事件:'close'
- 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
- Event: 'request' 事件:'request'
- Event: 'connection' 事件:'connection'
- Event: 'close' 事件:'close'
- Event: 'request' 事件:'request'
- Event: 'checkContinue' 事件:'checkContinue'
- Event: 'upgrade' 事件:'upgrade'
- Event: 'clientError' 事件:'clientError'
- http.createServer(requestListener)
- server.listen(port, [hostname], [callback])
- server.listen(path, [callback])
- server.close()
- 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 調試器
Synopsis 概要
An example of a web server written with Node which responds with 'HelloWorld':
下邊是一個用Node編寫的對所有請求簡單返回'Hello World‘的web服務器例子:
<code><span class="sh_keyword">var</span> http <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'http'</span><span class="sh_symbol">);</span> http<span class="sh_symbol">.</span><span class="sh_function">createServer</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">(</span>request<span class="sh_symbol">,</span> response<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> response<span class="sh_symbol">.</span><span class="sh_function">writeHead</span><span class="sh_symbol">(</span><span class="sh_number">200</span><span class="sh_symbol">,</span> <span class="sh_cbracket">{</span><span class="sh_string">'Content-Type'</span><span class="sh_symbol">:</span> <span class="sh_string">'text/plain'</span><span class="sh_cbracket">}</span><span class="sh_symbol">);</span> response<span class="sh_symbol">.</span><span class="sh_function">end</span><span class="sh_symbol">(</span><span class="sh_string">'Hello World</span><span class="sh_specialchar">\n</span><span class="sh_string">'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">).</span><span class="sh_function">listen</span><span class="sh_symbol">(</span><span class="sh_number">8124</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Server running at http://127.0.0.1:8124/'</span><span class="sh_symbol">);</span></code>
To run the server, put the code into a file called example.js
and executeit with the node program
要運行這個服務器程序,只要將上述代碼保存爲文件example.js
並用node程序執行此文件:
<code><span class="sh_symbol">></span> node example<span class="sh_symbol">.</span>js Server running at http<span class="sh_symbol">:</span><span class="sh_comment">//127.0.0.1:8124/</span></code>
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
例如:將一個新的搜索路徑插入到搜索列表的頭部。
<code>require<span class="sh_symbol">.</span>paths<span class="sh_symbol">.</span><span class="sh_function">unshift</span><span class="sh_symbol">(</span><span class="sh_string">'/usr/local/node'</span><span class="sh_symbol">);</span></code>
__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
<code>console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>__filename<span class="sh_symbol">);</span> <span class="sh_comment">// /Users/mjr/example.js</span></code>
__dirname
The dirname of the script being executed.
當前正在執行腳本所在的目錄名。
Example: running node example.js
from /Users/mjr
例如:在目錄/Users/mjr
下運行node example.js
<code>console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>__dirname<span class="sh_symbol">);</span> <span class="sh_comment">// /Users/mjr</span></code>
module
A reference to the current module. In particularmodule.exports
is the same as theexports
object. Seesrc/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
的內容爲:
<code><span class="sh_keyword">var</span> circle <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'./circle.js'</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span> <span class="sh_string">'The area of a circle of radius 4 is '</span> <span class="sh_symbol">+</span> circle<span class="sh_symbol">.</span><span class="sh_function">area</span><span class="sh_symbol">(</span><span class="sh_number">4</span><span class="sh_symbol">));</span></code>
The contents of circle.js
:
circle.js
的內容爲:
<code><span class="sh_keyword">var</span> PI <span class="sh_symbol">=</span> <span class="sh_predef_var">Math</span><span class="sh_symbol">.</span>PI<span class="sh_symbol">;</span> exports<span class="sh_symbol">.</span>area <span class="sh_symbol">=</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>r<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">return</span> PI <span class="sh_symbol">*</span> r <span class="sh_symbol">*</span> r<span class="sh_symbol">;</span> <span class="sh_cbracket">}</span><span class="sh_symbol">;</span> exports<span class="sh_symbol">.</span>circumference <span class="sh_symbol">=</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>r<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">return</span> <span class="sh_number">2</span> <span class="sh_symbol">*</span> PI <span class="sh_symbol">*</span> r<span class="sh_symbol">;</span> <span class="sh_cbracket">}</span><span class="sh_symbol">;</span></code>
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文件的例子如下面所示:
<code><span class="sh_cbracket">{</span> <span class="sh_string">"name"</span> <span class="sh_symbol">:</span> <span class="sh_string">"some-library"</span><span class="sh_symbol">,</span> <span class="sh_string">"main"</span> <span class="sh_symbol">:</span> <span class="sh_string">"./lib/some-library.js"</span> <span class="sh_cbracket">}</span></code>
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的算法邏輯:
<code><span class="sh_function">require</span><span class="sh_symbol">(</span>X<span class="sh_symbol">)</span> <span class="sh_number">1</span><span class="sh_symbol">.</span> If X is a core module<span class="sh_symbol">,</span> a<span class="sh_symbol">.</span> <span class="sh_keyword">return</span> the core module b<span class="sh_symbol">.</span> STOP <span class="sh_number">2</span><span class="sh_symbol">.</span> If X begins <span class="sh_keyword">with</span> `<span class="sh_symbol">.</span><span class="sh_regexp">/` or `/</span>`<span class="sh_symbol">,</span> a<span class="sh_symbol">.</span> <span class="sh_function">LOAD_AS_FILE</span><span class="sh_symbol">(</span>Y <span class="sh_symbol">+</span> X<span class="sh_symbol">)</span> b<span class="sh_symbol">.</span> <span class="sh_function">LOAD_AS_DIRECTORY</span><span class="sh_symbol">(</span>Y <span class="sh_symbol">+</span> X<span class="sh_symbol">)</span> <span class="sh_number">3</span><span class="sh_symbol">.</span> <span class="sh_function">LOAD_NODE_MODULES</span><span class="sh_symbol">(</span>X<span class="sh_symbol">,</span> <span class="sh_function">dirname</span><span class="sh_symbol">(</span>Y<span class="sh_symbol">))</span> <span class="sh_number">4</span><span class="sh_symbol">.</span> THROW <span class="sh_string">"not found"</span> <span class="sh_function">LOAD_AS_FILE</span><span class="sh_symbol">(</span>X<span class="sh_symbol">)</span> <span class="sh_number">1</span><span class="sh_symbol">.</span> If X is a file<span class="sh_symbol">,</span> load X as JavaScript text<span class="sh_symbol">.</span> STOP <span class="sh_number">2</span><span class="sh_symbol">.</span> If X<span class="sh_symbol">.</span>js is a file<span class="sh_symbol">,</span> load X<span class="sh_symbol">.</span>js as JavaScript text<span class="sh_symbol">.</span> STOP <span class="sh_number">3</span><span class="sh_symbol">.</span> If X<span class="sh_symbol">.</span>node is a file<span class="sh_symbol">,</span> load X<span class="sh_symbol">.</span>node as binary addon<span class="sh_symbol">.</span> STOP <span class="sh_function">LOAD_AS_DIRECTORY</span><span class="sh_symbol">(</span>X<span class="sh_symbol">)</span> <span class="sh_number">1</span><span class="sh_symbol">.</span> If <span class="sh_normal">X</span><span class="sh_symbol">/</span>package<span class="sh_symbol">.</span>json is a file<span class="sh_symbol">,</span> a<span class="sh_symbol">.</span> Parse <span class="sh_normal">X</span><span class="sh_symbol">/</span>package<span class="sh_symbol">.</span>json<span class="sh_symbol">,</span> and look <span class="sh_keyword">for</span> <span class="sh_string">"main"</span> field<span class="sh_symbol">.</span> b<span class="sh_symbol">.</span> let M <span class="sh_symbol">=</span> X <span class="sh_symbol">+</span> <span class="sh_symbol">(</span>json main field<span class="sh_symbol">)</span> c<span class="sh_symbol">.</span> <span class="sh_function">LOAD_AS_FILE</span><span class="sh_symbol">(</span>M<span class="sh_symbol">)</span> <span class="sh_number">2</span><span class="sh_symbol">.</span> <span class="sh_function">LOAD_AS_FILE</span><span class="sh_symbol">(</span><span class="sh_normal">X</span><span class="sh_symbol">/</span>index<span class="sh_symbol">)</span> <span class="sh_function">LOAD_NODE_MODULES</span><span class="sh_symbol">(</span>X<span class="sh_symbol">,</span> START<span class="sh_symbol">)</span> <span class="sh_number">1</span><span class="sh_symbol">.</span> let DIRS<span class="sh_symbol">=</span><span class="sh_function">NODE_MODULES_PATHS</span><span class="sh_symbol">(</span>START<span class="sh_symbol">)</span> <span class="sh_number">2</span><span class="sh_symbol">.</span> <span class="sh_keyword">for</span> each DIR <span class="sh_keyword">in</span> DIRS<span class="sh_symbol">:</span> a<span class="sh_symbol">.</span> <span class="sh_function">LOAD_AS_FILE</span><span class="sh_symbol">(</span><span class="sh_normal">DIR</span><span class="sh_symbol">/</span>X<span class="sh_symbol">)</span> b<span class="sh_symbol">.</span> <span class="sh_function">LOAD_AS_DIRECTORY</span><span class="sh_symbol">(</span><span class="sh_normal">DIR</span><span class="sh_symbol">/</span>X<span class="sh_symbol">)</span> <span class="sh_function">NODE_MODULES_PATHS</span><span class="sh_symbol">(</span>START<span class="sh_symbol">)</span> <span class="sh_number">1</span><span class="sh_symbol">.</span> let PARTS <span class="sh_symbol">=</span> path <span class="sh_function">split</span><span class="sh_symbol">(</span>START<span class="sh_symbol">)</span> <span class="sh_number">2</span><span class="sh_symbol">.</span> let ROOT <span class="sh_symbol">=</span> index of first instance of <span class="sh_string">"node_modules"</span> <span class="sh_keyword">in</span> PARTS<span class="sh_symbol">,</span> or <span class="sh_number">0</span> <span class="sh_number">3</span><span class="sh_symbol">.</span> let I <span class="sh_symbol">=</span> count of PARTS <span class="sh_symbol">-</span> <span class="sh_number">1</span> <span class="sh_number">4</span><span class="sh_symbol">.</span> let DIRS <span class="sh_symbol">=</span> <span class="sh_symbol">[]</span> <span class="sh_number">5</span><span class="sh_symbol">.</span> <span class="sh_keyword">while</span> I <span class="sh_symbol">></span> ROOT<span class="sh_symbol">,</span> a<span class="sh_symbol">.</span> <span class="sh_keyword">if</span> PARTS<span class="sh_symbol">[</span>I<span class="sh_symbol">]</span> <span class="sh_symbol">=</span> <span class="sh_string">"node_modules"</span> CONTINUE c<span class="sh_symbol">.</span> DIR <span class="sh_symbol">=</span> path <span class="sh_function">join</span><span class="sh_symbol">(</span>PARTS<span class="sh_symbol">[</span><span class="sh_number">0</span> <span class="sh_symbol">..</span> I<span class="sh_symbol">]</span> <span class="sh_symbol">+</span> <span class="sh_string">"node_modules"</span><span class="sh_symbol">)</span> b<span class="sh_symbol">.</span> DIRS <span class="sh_symbol">=</span> DIRS <span class="sh_symbol">+</span> DIR <span class="sh_number">6</span><span class="sh_symbol">.</span> <span class="sh_keyword">return</span> DIRS</code>
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如下設置:
<code><span class="sh_symbol">[</span> <span class="sh_string">'/home/micheil/.node_modules'</span><span class="sh_symbol">,</span> <span class="sh_string">'/usr/local/lib/node_modules'</span> <span class="sh_symbol">]</span></code>
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
環境變量被設置爲如下內容:
<code><span class="sh_regexp">/home/mi</span><span class="sh_normal">cheil</span><span class="sh_symbol">/.</span>node_modules<span class="sh_symbol">:</span><span class="sh_regexp">/usr/</span><span class="sh_normal">local</span><span class="sh_symbol">/</span><span class="sh_normal">lib</span><span class="sh_symbol">/</span>node_modules</code>
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:
下述做法不會其他你期望的任何效果:
<code>require<span class="sh_symbol">.</span>paths <span class="sh_symbol">=</span> <span class="sh_symbol">[</span> <span class="sh_string">'/usr/lib/node'</span> <span class="sh_symbol">];</span></code>
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:
如果你這樣做:
<code>require<span class="sh_symbol">.</span>paths<span class="sh_symbol">.</span><span class="sh_function">push</span><span class="sh_symbol">(</span><span class="sh_string">'./lib'</span><span class="sh_symbol">);</span></code>
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 didrequire('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 thefoo
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 thebar
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 the
v8.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, in
src/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的小例子,來達到如下模塊同樣的效果:
<code>exports<span class="sh_symbol">.</span>hello <span class="sh_symbol">=</span> <span class="sh_string">'world'</span><span class="sh_symbol">;</span></code>
To get started we create a file hello.cc
:
首先我們需要創建一個hello.cc
文件:
<code>#include <span class="sh_symbol"><</span>v8<span class="sh_symbol">.</span>h<span class="sh_symbol">></span> using namespace v8<span class="sh_symbol">;</span> extern <span class="sh_string">"C"</span> void <span class="sh_function">init</span> <span class="sh_symbol">(</span>Handle<span class="sh_symbol"><</span><span class="sh_predef_func">Object</span><span class="sh_symbol">></span> target<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> HandleScope scope<span class="sh_symbol">;</span> target<span class="sh_symbol">-></span><span class="sh_function">Set</span><span class="sh_symbol">(</span><span class="sh_predef_func">String</span><span class="sh_symbol">::</span><span class="sh_function">New</span><span class="sh_symbol">(</span><span class="sh_string">"hello"</span><span class="sh_symbol">),</span> <span class="sh_predef_func">String</span><span class="sh_symbol">::</span><span class="sh_function">New</span><span class="sh_symbol">(</span><span class="sh_string">"world"</span><span class="sh_symbol">));</span> <span class="sh_cbracket">}</span></code>
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
的文件:
<code>srcdir <span class="sh_symbol">=</span> <span class="sh_string">'.'</span> blddir <span class="sh_symbol">=</span> <span class="sh_string">'build'</span> VERSION <span class="sh_symbol">=</span> <span class="sh_string">'0.0.1'</span> def <span class="sh_function">set_options</span><span class="sh_symbol">(</span>opt<span class="sh_symbol">):</span> opt<span class="sh_symbol">.</span><span class="sh_function">tool_options</span><span class="sh_symbol">(</span><span class="sh_string">'compiler_cxx'</span><span class="sh_symbol">)</span> def <span class="sh_function">configure</span><span class="sh_symbol">(</span>conf<span class="sh_symbol">):</span> conf<span class="sh_symbol">.</span><span class="sh_function">check_tool</span><span class="sh_symbol">(</span><span class="sh_string">'compiler_cxx'</span><span class="sh_symbol">)</span> conf<span class="sh_symbol">.</span><span class="sh_function">check_tool</span><span class="sh_symbol">(</span><span class="sh_string">'node_addon'</span><span class="sh_symbol">)</span> def <span class="sh_function">build</span><span class="sh_symbol">(</span>bld<span class="sh_symbol">):</span> obj <span class="sh_symbol">=</span> bld<span class="sh_symbol">.</span><span class="sh_function">new_task_gen</span><span class="sh_symbol">(</span><span class="sh_string">'cxx'</span><span class="sh_symbol">,</span> <span class="sh_string">'shlib'</span><span class="sh_symbol">,</span> <span class="sh_string">'node_addon'</span><span class="sh_symbol">)</span> obj<span class="sh_symbol">.</span>target <span class="sh_symbol">=</span> <span class="sh_string">'hello'</span> obj<span class="sh_symbol">.</span>source <span class="sh_symbol">=</span> <span class="sh_string">'hello.cc'</span></code>
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
函數:
<code>extern <span class="sh_string">'C'</span> void <span class="sh_function">init</span> <span class="sh_symbol">(</span>Handle<span class="sh_symbol"><</span><span class="sh_predef_func">Object</span><span class="sh_symbol">></span> target<span class="sh_symbol">)</span></code>
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
行爲的示例:
<code>process<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'exit'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> process<span class="sh_symbol">.</span><span class="sh_function">nextTick</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'This will not run'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'About to exit.'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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
事件的示例:
<code>process<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'uncaughtException'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Caught exception: '</span> <span class="sh_symbol">+</span> err<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_function">setTimeout</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'This will still run.'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_number">500</span><span class="sh_symbol">);</span> <span class="sh_comment">// Intentionally cause an exception, but don't catch it.</span> <span class="sh_function">nonexistentFunc</span><span class="sh_symbol">();</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'This will not run.'</span><span class="sh_symbol">);</span></code>
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
的示例:
<code><span class="sh_comment">// Start reading from stdin so we don't exit.</span> process<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">resume</span><span class="sh_symbol">();</span> process<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'SIGINT'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Got SIGINT. Press Control-D to exit.'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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
的定義。
<code>console<span class="sh_symbol">.</span>log <span class="sh_symbol">=</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>d<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> process<span class="sh_symbol">.</span>stdout<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span>d <span class="sh_symbol">+</span> <span class="sh_string">'</span><span class="sh_specialchar">\n</span><span class="sh_string">'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">;</span></code>
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:
示例:打開標準輸入與監聽兩個事件:
<code>process<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">resume</span><span class="sh_symbol">();</span> process<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">setEncoding</span><span class="sh_symbol">(</span><span class="sh_string">'utf8'</span><span class="sh_symbol">);</span> process<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>chunk<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> process<span class="sh_symbol">.</span>stdout<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span><span class="sh_string">'data: '</span> <span class="sh_symbol">+</span> chunk<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> process<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'end'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> process<span class="sh_symbol">.</span>stdout<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span><span class="sh_string">'end'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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文件的文件名。接下來的元素則是附加的命令行參數。
<code><span class="sh_comment">// print process.argv</span> process<span class="sh_symbol">.</span>argv<span class="sh_symbol">.</span><span class="sh_function">forEach</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">(</span>val<span class="sh_symbol">,</span> index<span class="sh_symbol">,</span> array<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>index <span class="sh_symbol">+</span> <span class="sh_string">': '</span> <span class="sh_symbol">+</span> val<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
This will generate:
這產生如下的信息:
<code>$ node process<span class="sh_number">-2</span><span class="sh_symbol">.</span>js one two<span class="sh_symbol">=</span>three four <span class="sh_number">0</span><span class="sh_symbol">:</span> node <span class="sh_number">1</span><span class="sh_symbol">:</span> <span class="sh_regexp">/Users/m</span><span class="sh_normal">jr</span><span class="sh_symbol">/</span><span class="sh_normal">work</span><span class="sh_symbol">/</span><span class="sh_normal">node</span><span class="sh_symbol">/</span>process<span class="sh_number">-2</span><span class="sh_symbol">.</span>js <span class="sh_number">2</span><span class="sh_symbol">:</span> one <span class="sh_number">3</span><span class="sh_symbol">:</span> two<span class="sh_symbol">=</span>three <span class="sh_number">4</span><span class="sh_symbol">:</span> four</code>
process.execPath
This is the absolute pathname of the executable that started the process.
這是一個啓動該進程的可執行程序的絕對路徑名。
Example:
例如:
<code><span class="sh_regexp">/usr/</span><span class="sh_normal">local</span><span class="sh_symbol">/</span><span class="sh_normal">bin</span><span class="sh_symbol">/</span>node</code>
process.chdir(directory)
Changes the current working directory of the process or throws an exception if that fails.
改變進程的當前工作目錄,如果操作失敗則拋出異常。
<code>console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Starting directory: '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span><span class="sh_function">cwd</span><span class="sh_symbol">());</span> <span class="sh_keyword">try</span> <span class="sh_cbracket">{</span> process<span class="sh_symbol">.</span><span class="sh_function">chdir</span><span class="sh_symbol">(</span><span class="sh_string">'/tmp'</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'New directory: '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span><span class="sh_function">cwd</span><span class="sh_symbol">());</span> <span class="sh_cbracket">}</span> <span class="sh_keyword">catch</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'chdir: '</span> <span class="sh_symbol">+</span> err<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span></code>
process.cwd()
Returns the current working directory of the process.
返回進程的當前工作目錄。
<code>console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Current directory: '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span><span class="sh_function">cwd</span><span class="sh_symbol">());</span></code>
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'(失敗)代碼退出的示例:
<code>process<span class="sh_symbol">.</span><span class="sh_function">exit</span><span class="sh_symbol">(</span><span class="sh_number">1</span><span class="sh_symbol">);</span></code>
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,不是羣組名稱。
<code>console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Current gid: '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span><span class="sh_function">getgid</span><span class="sh_symbol">());</span></code>
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。
<code>console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Current gid: '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span><span class="sh_function">getgid</span><span class="sh_symbol">());</span> <span class="sh_keyword">try</span> <span class="sh_cbracket">{</span> process<span class="sh_symbol">.</span><span class="sh_function">setgid</span><span class="sh_symbol">(</span><span class="sh_number">501</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'New gid: '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span><span class="sh_function">getgid</span><span class="sh_symbol">());</span> <span class="sh_cbracket">}</span> <span class="sh_keyword">catch</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Failed to set gid: '</span> <span class="sh_symbol">+</span> err<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span></code>
process.getuid()
Gets the user identity of the process. (See getuid(2).)This is the numerical userid, not the username.
獲取進程的用戶ID(詳見getgid(2))。這是一個數字用戶ID,不是用戶名。
<code>console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Current uid: '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span><span class="sh_function">getuid</span><span class="sh_symbol">());</span></code>
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。
<code>console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Current uid: '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span><span class="sh_function">getuid</span><span class="sh_symbol">());</span> <span class="sh_keyword">try</span> <span class="sh_cbracket">{</span> process<span class="sh_symbol">.</span><span class="sh_function">setuid</span><span class="sh_symbol">(</span><span class="sh_number">501</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'New uid: '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span><span class="sh_function">getuid</span><span class="sh_symbol">());</span> <span class="sh_cbracket">}</span> <span class="sh_keyword">catch</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Failed to set uid: '</span> <span class="sh_symbol">+</span> err<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span></code>
process.version
A compiled-in property that exposes NODE_VERSION
.
一個編譯內置的屬性,用於顯示NODE_VERSION
(Node版本)。
<code>console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Version: '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span>version<span class="sh_symbol">);</span></code>
process.installPrefix
A compiled-in property that exposes NODE_PREFIX
.
一個編譯內置的屬性,用於顯示NODE_PREFIX
(Node安裝路徑前綴)。
<code>console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Prefix: '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span>installPrefix<span class="sh_symbol">);</span></code>
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:
一個給自己發送信號的示例:
<code>process<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'SIGHUP'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Got SIGHUP signal.'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_function">setTimeout</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Exiting.'</span><span class="sh_symbol">);</span> process<span class="sh_symbol">.</span><span class="sh_function">exit</span><span class="sh_symbol">(</span><span class="sh_number">0</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_number">100</span><span class="sh_symbol">);</span> process<span class="sh_symbol">.</span><span class="sh_function">kill</span><span class="sh_symbol">(</span>process<span class="sh_symbol">.</span>pid<span class="sh_symbol">,</span> <span class="sh_string">'SIGHUP'</span><span class="sh_symbol">);</span></code>
process.pid
The PID of the process.
進程的PID。
<code>console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'This process is pid '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span>pid<span class="sh_symbol">);</span></code>
process.title
Getter/setter to set what is displayed in 'ps'.
獲取或設置在'ps'命令中顯示的進程的標題。
process.platform
What platform you're running on. 'linux2'
, 'darwin'
, etc.
運行Node的平臺信息,如'linux2',
'darwin'`等等。
<code>console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'This platform is '</span> <span class="sh_symbol">+</span> process<span class="sh_symbol">.</span>platform<span class="sh_symbol">);</span></code>
process.memoryUsage()
Returns an object describing the memory usage of the Node process.
返回一個描述Node進程內存使用情況的對象。
<code><span class="sh_keyword">var</span> util <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'util'</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>util<span class="sh_symbol">.</span><span class="sh_function">inspect</span><span class="sh_symbol">(</span>process<span class="sh_symbol">.</span><span class="sh_function">memoryUsage</span><span class="sh_symbol">()));</span></code>
This will generate:
這會生成如下信息:
<code><span class="sh_cbracket">{</span> rss<span class="sh_symbol">:</span> <span class="sh_number">4935680</span><span class="sh_symbol">,</span> vsize<span class="sh_symbol">:</span> <span class="sh_number">41893888</span><span class="sh_symbol">,</span> heapTotal<span class="sh_symbol">:</span> <span class="sh_number">1826816</span><span class="sh_symbol">,</span> heapUsed<span class="sh_symbol">:</span> <span class="sh_number">650472</span> <span class="sh_cbracket">}</span></code>
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)
的一個別名,因爲它有效率多了。
<code>process<span class="sh_symbol">.</span><span class="sh_function">nextTick</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'nextTick callback'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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
那麼返回舊的掩碼,否則返回當前的掩碼。
<code><span class="sh_keyword">var</span> oldmask<span class="sh_symbol">,</span> newmask <span class="sh_symbol">=</span> <span class="sh_number">0644</span><span class="sh_symbol">;</span> oldmask <span class="sh_symbol">=</span> process<span class="sh_symbol">.</span><span class="sh_function">umask</span><span class="sh_symbol">(</span>newmask<span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Changed umask from: '</span> <span class="sh_symbol">+</span> oldmask<span class="sh_symbol">.</span><span class="sh_function">toString</span><span class="sh_symbol">(</span><span class="sh_number">8</span><span class="sh_symbol">)</span> <span class="sh_symbol">+</span> <span class="sh_string">' to '</span> <span class="sh_symbol">+</span> newmask<span class="sh_symbol">.</span><span class="sh_function">toString</span><span class="sh_symbol">(</span><span class="sh_number">8</span><span class="sh_symbol">));</span></code>
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
標準錯誤。調用此函數時將阻塞當前進程直到輸出完成。
<code><span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'util'</span><span class="sh_symbol">).</span><span class="sh_function">debug</span><span class="sh_symbol">(</span><span class="sh_string">'message on stderr'</span><span class="sh_symbol">);</span></code>
util.log(string)
Output with timestamp on stdout
.
將string
參數的內容加上當前時間戳,輸出到stdout
標準輸出。
<code><span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'util'</span><span class="sh_symbol">).</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Timestmaped message.'</span><span class="sh_symbol">);</span></code>
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
對象所有屬性的例子如下:
<code><span class="sh_keyword">var</span> util <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'util'</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>util<span class="sh_symbol">.</span><span class="sh_function">inspect</span><span class="sh_symbol">(</span>util<span class="sh_symbol">,</span> <span class="sh_keyword">true</span><span class="sh_symbol">,</span> <span class="sh_keyword">null</span><span class="sh_symbol">));</span></code>
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
構造函數。
<code><span class="sh_keyword">var</span> util <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">"util"</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> events <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">"events"</span><span class="sh_symbol">);</span> <span class="sh_keyword">function</span> <span class="sh_function">MyStream</span><span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> events<span class="sh_symbol">.</span>EventEmitter<span class="sh_symbol">.</span><span class="sh_function">call</span><span class="sh_symbol">(</span><span class="sh_keyword">this</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span> util<span class="sh_symbol">.</span><span class="sh_function">inherits</span><span class="sh_symbol">(</span>MyStream<span class="sh_symbol">,</span> events<span class="sh_symbol">.</span>EventEmitter<span class="sh_symbol">);</span> MyStream<span class="sh_symbol">.</span><span class="sh_keyword">prototype</span><span class="sh_symbol">.</span>write <span class="sh_symbol">=</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>data<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">this</span><span class="sh_symbol">.</span><span class="sh_function">emit</span><span class="sh_symbol">(</span><span class="sh_string">"data"</span><span class="sh_symbol">,</span> data<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span> <span class="sh_keyword">var</span> stream <span class="sh_symbol">=</span> <span class="sh_keyword">new</span> <span class="sh_function">MyStream</span><span class="sh_symbol">();</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>stream <span class="sh_keyword">instanceof</span> events<span class="sh_symbol">.</span>EventEmitter<span class="sh_symbol">);</span> <span class="sh_comment">// true</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>MyStream<span class="sh_symbol">.</span>super_ <span class="sh_symbol">===</span> events<span class="sh_symbol">.</span>EventEmitter<span class="sh_symbol">);</span> <span class="sh_comment">// true</span> stream<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">"data"</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>data<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Received data: "'</span> <span class="sh_symbol">+</span> data <span class="sh_symbol">+</span> <span class="sh_string">'"'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">)</span> stream<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span><span class="sh_string">"It works!"</span><span class="sh_symbol">);</span> <span class="sh_comment">// Received data: "It works!"</span></code>
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.
將一個監聽器添加到指定事件的監聽器數組的末尾。
<code>server<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'connection'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>stream<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'someone connected!'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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.
爲事件添加一次性的監聽器。該監聽器在事件第一次觸發時執行,過後將被移除。
<code>server<span class="sh_symbol">.</span><span class="sh_function">once</span><span class="sh_symbol">(</span><span class="sh_string">'connection'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>stream<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Ah, we have our first user!'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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.
將監聽器從指定事件的監聽器數組中移除出去。小心:此操作將改變監聽器數組的下標。
<code><span class="sh_keyword">var</span> callback <span class="sh_symbol">=</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>stream<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'someone connected!'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">;</span> server<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'connection'</span><span class="sh_symbol">,</span> callback<span class="sh_symbol">);</span> <span class="sh_comment">// ...</span> server<span class="sh_symbol">.</span><span class="sh_function">removeListener</span><span class="sh_symbol">(</span><span class="sh_string">'connection'</span><span class="sh_symbol">,</span> callback<span class="sh_symbol">);</span></code>
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.
返回指定事件的監聽器數組對象,你可以對該數組進行操作,比如說刪除監聽器等。
<code>server<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'connection'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>stream<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'someone connected!'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>util<span class="sh_symbol">.</span><span class="sh_function">inspect</span><span class="sh_symbol">(</span>server<span class="sh_symbol">.</span><span class="sh_function">listeners</span><span class="sh_symbol">(</span><span class="sh_string">'connection'</span><span class="sh_symbol">));</span> <span class="sh_comment">// [ [Function] ]</span></code>
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,然後輸出:
<code>buf <span class="sh_symbol">=</span> <span class="sh_keyword">new</span> <span class="sh_function">Buffer</span><span class="sh_symbol">(</span><span class="sh_number">256</span><span class="sh_symbol">);</span> len <span class="sh_symbol">=</span> buf<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span><span class="sh_string">'</span><span class="sh_specialchar">\u</span><span class="sh_string">00bd + </span><span class="sh_specialchar">\u</span><span class="sh_string">00bc = </span><span class="sh_specialchar">\u</span><span class="sh_string">00be'</span><span class="sh_symbol">,</span> <span class="sh_number">0</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>len <span class="sh_symbol">+</span> <span class="sh_string">" bytes: "</span> <span class="sh_symbol">+</span> buf<span class="sh_symbol">.</span><span class="sh_function">toString</span><span class="sh_symbol">(</span><span class="sh_string">'utf8'</span><span class="sh_symbol">,</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> len<span class="sh_symbol">));</span> <span class="sh_comment">// 12 bytes: ½ + ¼ = ¾</span></code>
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中:
<code>str <span class="sh_symbol">=</span> <span class="sh_string">"node.js"</span><span class="sh_symbol">;</span> buf <span class="sh_symbol">=</span> <span class="sh_keyword">new</span> <span class="sh_function">Buffer</span><span class="sh_symbol">(</span>str<span class="sh_symbol">.</span>length<span class="sh_symbol">);</span> <span class="sh_keyword">for</span> <span class="sh_symbol">(</span><span class="sh_keyword">var</span> i <span class="sh_symbol">=</span> <span class="sh_number">0</span><span class="sh_symbol">;</span> i <span class="sh_symbol"><</span> str<span class="sh_symbol">.</span>length <span class="sh_symbol">;</span> i<span class="sh_symbol">++)</span> <span class="sh_cbracket">{</span> buf<span class="sh_symbol">[</span>i<span class="sh_symbol">]</span> <span class="sh_symbol">=</span> str<span class="sh_symbol">.</span><span class="sh_function">charCodeAt</span><span class="sh_symbol">(</span>i<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>buf<span class="sh_symbol">);</span> <span class="sh_comment">// node.js</span></code>
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:
例如:
<code>str <span class="sh_symbol">=</span> <span class="sh_string">'</span><span class="sh_specialchar">\u</span><span class="sh_string">00bd + </span><span class="sh_specialchar">\u</span><span class="sh_string">00bc = </span><span class="sh_specialchar">\u</span><span class="sh_string">00be'</span><span class="sh_symbol">;</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>str <span class="sh_symbol">+</span> <span class="sh_string">": "</span> <span class="sh_symbol">+</span> str<span class="sh_symbol">.</span>length <span class="sh_symbol">+</span> <span class="sh_string">" characters, "</span> <span class="sh_symbol">+</span> Buffer<span class="sh_symbol">.</span><span class="sh_function">byteLength</span><span class="sh_symbol">(</span>str<span class="sh_symbol">,</span> <span class="sh_string">'utf8'</span><span class="sh_symbol">)</span> <span class="sh_symbol">+</span> <span class="sh_string">" bytes"</span><span class="sh_symbol">);</span> <span class="sh_comment">// ½ + ¼ = ¾: 9 characters, 12 bytes</span></code>
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內容的變化而變化。
<code>buf <span class="sh_symbol">=</span> <span class="sh_keyword">new</span> <span class="sh_function">Buffer</span><span class="sh_symbol">(</span><span class="sh_number">1234</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>buf<span class="sh_symbol">.</span>length<span class="sh_symbol">);</span> buf<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span><span class="sh_string">"some string"</span><span class="sh_symbol">,</span> <span class="sh_string">"ascii"</span><span class="sh_symbol">,</span> <span class="sh_number">0</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>buf<span class="sh_symbol">.</span>length<span class="sh_symbol">);</span> <span class="sh_comment">// 1234</span> <span class="sh_comment">// 1234</span></code>
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字節:
<code>buf1 <span class="sh_symbol">=</span> <span class="sh_keyword">new</span> <span class="sh_function">Buffer</span><span class="sh_symbol">(</span><span class="sh_number">26</span><span class="sh_symbol">);</span> buf2 <span class="sh_symbol">=</span> <span class="sh_keyword">new</span> <span class="sh_function">Buffer</span><span class="sh_symbol">(</span><span class="sh_number">26</span><span class="sh_symbol">);</span> <span class="sh_keyword">for</span> <span class="sh_symbol">(</span><span class="sh_keyword">var</span> i <span class="sh_symbol">=</span> <span class="sh_number">0</span> <span class="sh_symbol">;</span> i <span class="sh_symbol"><</span> <span class="sh_number">26</span> <span class="sh_symbol">;</span> i<span class="sh_symbol">++)</span> <span class="sh_cbracket">{</span> buf1<span class="sh_symbol">[</span>i<span class="sh_symbol">]</span> <span class="sh_symbol">=</span> i <span class="sh_symbol">+</span> <span class="sh_number">97</span><span class="sh_symbol">;</span> <span class="sh_comment">// 97 is ASCII a</span> buf2<span class="sh_symbol">[</span>i<span class="sh_symbol">]</span> <span class="sh_symbol">=</span> <span class="sh_number">33</span><span class="sh_symbol">;</span> <span class="sh_comment">// ASCII !</span> <span class="sh_cbracket">}</span> buf1<span class="sh_symbol">.</span><span class="sh_function">copy</span><span class="sh_symbol">(</span>buf2<span class="sh_symbol">,</span> <span class="sh_number">8</span><span class="sh_symbol">,</span> <span class="sh_number">16</span><span class="sh_symbol">,</span> <span class="sh_number">20</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>buf2<span class="sh_symbol">.</span><span class="sh_function">toString</span><span class="sh_symbol">(</span><span class="sh_string">'ascii'</span><span class="sh_symbol">,</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> <span class="sh_number">25</span><span class="sh_symbol">));</span> <span class="sh_comment">// !!!!!!!!qrst!!!!!!!!!!!!!</span></code>
buffer.slice(start, end=buffer.length)
Returns a new buffer which references thesame memory as the old, but offset and cropped by thestart
andend
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中修改一個字節:
<code><span class="sh_keyword">var</span> buf1 <span class="sh_symbol">=</span> <span class="sh_keyword">new</span> <span class="sh_function">Buffer</span><span class="sh_symbol">(</span><span class="sh_number">26</span><span class="sh_symbol">);</span> <span class="sh_keyword">for</span> <span class="sh_symbol">(</span><span class="sh_keyword">var</span> i <span class="sh_symbol">=</span> <span class="sh_number">0</span> <span class="sh_symbol">;</span> i <span class="sh_symbol"><</span> <span class="sh_number">26</span> <span class="sh_symbol">;</span> i<span class="sh_symbol">++)</span> <span class="sh_cbracket">{</span> buf1<span class="sh_symbol">[</span>i<span class="sh_symbol">]</span> <span class="sh_symbol">=</span> i <span class="sh_symbol">+</span> <span class="sh_number">97</span><span class="sh_symbol">;</span> <span class="sh_comment">// 97 is ASCII a</span> <span class="sh_cbracket">}</span> <span class="sh_keyword">var</span> buf2 <span class="sh_symbol">=</span> buf1<span class="sh_symbol">.</span><span class="sh_function">slice</span><span class="sh_symbol">(</span><span class="sh_number">0</span><span class="sh_symbol">,</span> <span class="sh_number">3</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>buf2<span class="sh_symbol">.</span><span class="sh_function">toString</span><span class="sh_symbol">(</span><span class="sh_string">'ascii'</span><span class="sh_symbol">,</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> buf2<span class="sh_symbol">.</span>length<span class="sh_symbol">));</span> buf1<span class="sh_symbol">[</span><span class="sh_number">0</span><span class="sh_symbol">]</span> <span class="sh_symbol">=</span> <span class="sh_number">33</span><span class="sh_symbol">;</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>buf2<span class="sh_symbol">.</span><span class="sh_function">toString</span><span class="sh_symbol">(</span><span class="sh_string">'ascii'</span><span class="sh_symbol">,</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> buf2<span class="sh_symbol">.</span>length<span class="sh_symbol">));</span> <span class="sh_comment">// abc</span> <span class="sh_comment">// !bc</span></code>
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'
, ordestroy()
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
命令:
<code>process<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">resume</span><span class="sh_symbol">();</span> process<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">pipe</span><span class="sh_symbol">(</span>process<span class="sh_symbol">.</span>stdout<span class="sh_symbol">);</span></code>
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事件發生後被寫入。
<code>process<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">resume</span><span class="sh_symbol">();</span> process<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">pipe</span><span class="sh_symbol">(</span>process<span class="sh_symbol">.</span>stdout<span class="sh_symbol">,</span> <span class="sh_cbracket">{</span> end<span class="sh_symbol">:</span> <span class="sh_keyword">false</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> process<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">"end"</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> process<span class="sh_symbol">.</span>stdout<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span><span class="sh_string">"Goodbye</span><span class="sh_specialchar">\n</span><span class="sh_string">"</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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 keykey
:爲字符串型,PEM編碼的私鑰。 -
cert
: a string holding the PEM encoded certificatecert
:爲字符串型,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基於公鑰/私鑰的非對稱加密體系,每一個客戶端與服務器都需要擁有一個私有密鑰。私有密鑰可用如下方式生成:
<code>openssl genrsa <span class="sh_symbol">-</span>out ryans<span class="sh_symbol">-</span>key<span class="sh_symbol">.</span>pem <span class="sh_number">1024</span></code>
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(證書籤名請求)文件。方法如下:
<code>openssl req <span class="sh_symbol">-</span><span class="sh_keyword">new</span> <span class="sh_symbol">-</span>key ryans<span class="sh_symbol">-</span>key<span class="sh_symbol">.</span>pem <span class="sh_symbol">-</span>out ryans<span class="sh_symbol">-</span>csr<span class="sh_symbol">.</span>pem</code>
To create a self-signed certificate with the CSR, do this:
要使用CSR文件生成一個自簽名的數字證書,方法如下:
<code>openssl x509 <span class="sh_symbol">-</span>req <span class="sh_symbol">-</span><span class="sh_keyword">in</span> ryans<span class="sh_symbol">-</span>csr<span class="sh_symbol">.</span>pem <span class="sh_symbol">-</span>signkey ryans<span class="sh_symbol">-</span>key<span class="sh_symbol">.</span>pem <span class="sh_symbol">-</span>out ryans<span class="sh_symbol">-</span>cert<span class="sh_symbol">.</span>pem</code>
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 orBuffer
containing the private key of the server inPEM format. (Required)key
:包含服務器私鑰的字符串或Buffer
對象。密鑰的格式爲PEM。(必選) -
cert
: A string orBuffer
containing the certificate key of the server inPEM format.cert
:包含服務器數字證書密鑰的字符串或Buffer
對象。密鑰的格式爲PEM。 -
ca
: An array of strings orBuffer
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:
下面是一個簡單的回聲服務器的例子:
<code><span class="sh_keyword">var</span> tls <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'tls'</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> fs <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'fs'</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> options <span class="sh_symbol">=</span> <span class="sh_cbracket">{</span> key<span class="sh_symbol">:</span> fs<span class="sh_symbol">.</span><span class="sh_function">readFileSync</span><span class="sh_symbol">(</span><span class="sh_string">'server-key.pem'</span><span class="sh_symbol">),</span> cert<span class="sh_symbol">:</span> fs<span class="sh_symbol">.</span><span class="sh_function">readFileSync</span><span class="sh_symbol">(</span><span class="sh_string">'server-cert.pem'</span><span class="sh_symbol">)</span> <span class="sh_cbracket">}</span><span class="sh_symbol">;</span> tls<span class="sh_symbol">.</span><span class="sh_function">createServer</span><span class="sh_symbol">(</span>options<span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>s<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> s<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span><span class="sh_string">"welcome!</span><span class="sh_specialchar">\n</span><span class="sh_string">"</span><span class="sh_symbol">);</span> s<span class="sh_symbol">.</span><span class="sh_function">pipe</span><span class="sh_symbol">(</span>s<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">).</span><span class="sh_function">listen</span><span class="sh_symbol">(</span><span class="sh_number">8000</span><span class="sh_symbol">);</span></code>
You can test this server by connecting to it with openssl s_client
:
你可以使用openssl s_client
連接到這個服務器進行測試:
<code>openssl s_client <span class="sh_symbol">-</span>connect <span class="sh_number">127.0.0.1</span><span class="sh_symbol">:</span><span class="sh_number">8000</span></code>
tls.createServer(options, secureConnectionListener)
This is a constructor for the tls.Server
class. The options objecthas these possibilities:
這是tls.Server
類的構造函數。參數options對象可以包含下列內容:
-
key
: A string orBuffer
containing the private key of the server inPEM format. (Required)key
:包含服務器私鑰的字符串或Buffer
對象。密鑰的格式爲PEM。(必選) -
cert
: A string orBuffer
containing the certificate key of the server inPEM format. (Required)cert
:包含服務器數字證書密鑰的字符串或Buffer
對象。密鑰的格式爲PEM。(必選) -
ca
: An array of strings orBuffer
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
: Iftrue
the server will request a certificate fromclients that connect and attempt to verify that certificate. Default:false
.requestCert
:如果設爲true
則服務器會向建立連接的客戶端要求一個數字證書,並且試圖去驗證這份數字證書。默認爲false
。 -
rejectUnauthorized
: Iftrue
the server will reject any connectionwhich is not authorized with the list of supplied CAs. This option onlyhas an effect ifrequestCert
istrue
. 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:
這裏是一個異步調用的例子:
<code><span class="sh_keyword">var</span> fs <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'fs'</span><span class="sh_symbol">);</span> fs<span class="sh_symbol">.</span><span class="sh_function">unlink</span><span class="sh_symbol">(</span><span class="sh_string">'/tmp/hello'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_keyword">throw</span> err<span class="sh_symbol">;</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'successfully deleted /tmp/hello'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
Here is the synchronous version:
這裏是進行相同操作的同步調用的例子:
<code><span class="sh_keyword">var</span> fs <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'fs'</span><span class="sh_symbol">);</span> fs<span class="sh_symbol">.</span><span class="sh_function">unlinkSync</span><span class="sh_symbol">(</span><span class="sh_string">'/tmp/hello'</span><span class="sh_symbol">)</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'successfully deleted /tmp/hello'</span><span class="sh_symbol">);</span></code>
With the asynchronous methods there is no guaranteed ordering. So thefollowing is prone to error:
由於異步方法調用無法保證執行的順序,所以下面的代碼容易導致出現錯誤。
<code>fs<span class="sh_symbol">.</span><span class="sh_function">rename</span><span class="sh_symbol">(</span><span class="sh_string">'/tmp/hello'</span><span class="sh_symbol">,</span> <span class="sh_string">'/tmp/world'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_keyword">throw</span> err<span class="sh_symbol">;</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'renamed complete'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> fs<span class="sh_symbol">.</span><span class="sh_function">stat</span><span class="sh_symbol">(</span><span class="sh_string">'/tmp/world'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">,</span> stats<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_keyword">throw</span> err<span class="sh_symbol">;</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'stats: '</span> <span class="sh_symbol">+</span> JSON<span class="sh_symbol">.</span><span class="sh_function">stringify</span><span class="sh_symbol">(</span>stats<span class="sh_symbol">));</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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
之前執行,正確的做法是鏈式調用回調函數。
<code>fs<span class="sh_symbol">.</span><span class="sh_function">rename</span><span class="sh_symbol">(</span><span class="sh_string">'/tmp/hello'</span><span class="sh_symbol">,</span> <span class="sh_string">'/tmp/world'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_keyword">throw</span> err<span class="sh_symbol">;</span> fs<span class="sh_symbol">.</span><span class="sh_function">stat</span><span class="sh_symbol">(</span><span class="sh_string">'/tmp/world'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">,</span> stats<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_keyword">throw</span> err<span class="sh_symbol">;</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'stats: '</span> <span class="sh_symbol">+</span> JSON<span class="sh_symbol">.</span><span class="sh_function">stringify</span><span class="sh_symbol">(</span>stats<span class="sh_symbol">));</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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
的一個對象,如下所示:
<code><span class="sh_cbracket">{</span> dev<span class="sh_symbol">:</span> <span class="sh_number">2049</span><span class="sh_symbol">,</span> ino<span class="sh_symbol">:</span> <span class="sh_number">305352</span><span class="sh_symbol">,</span> mode<span class="sh_symbol">:</span> <span class="sh_number">16877</span><span class="sh_symbol">,</span> nlink<span class="sh_symbol">:</span> <span class="sh_number">12</span><span class="sh_symbol">,</span> uid<span class="sh_symbol">:</span> <span class="sh_number">1000</span><span class="sh_symbol">,</span> gid<span class="sh_symbol">:</span> <span class="sh_number">1000</span><span class="sh_symbol">,</span> rdev<span class="sh_symbol">:</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> size<span class="sh_symbol">:</span> <span class="sh_number">4096</span><span class="sh_symbol">,</span> blksize<span class="sh_symbol">:</span> <span class="sh_number">4096</span><span class="sh_symbol">,</span> blocks<span class="sh_symbol">:</span> <span class="sh_number">8</span><span class="sh_symbol">,</span> atime<span class="sh_symbol">:</span> <span class="sh_string">'2009-06-29T11:11:55Z'</span><span class="sh_symbol">,</span> mtime<span class="sh_symbol">:</span> <span class="sh_string">'2009-06-29T11:11:40Z'</span><span class="sh_symbol">,</span> ctime<span class="sh_symbol">:</span> <span class="sh_string">'2009-06-29T11:11:40Z'</span> <span class="sh_cbracket">}</span></code>
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:
異步讀取一個文件的所有內容,例子如下:
<code>fs<span class="sh_symbol">.</span><span class="sh_function">readFile</span><span class="sh_symbol">(</span><span class="sh_string">'/etc/passwd'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">,</span> data<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_keyword">throw</span> err<span class="sh_symbol">;</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>data<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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:
例子:
<code>fs<span class="sh_symbol">.</span><span class="sh_function">writeFile</span><span class="sh_symbol">(</span><span class="sh_string">'message.txt'</span><span class="sh_symbol">,</span> <span class="sh_string">'Hello Node'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_keyword">throw</span> err<span class="sh_symbol">;</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'It</span><span class="sh_specialchar">\'</span><span class="sh_string">s saved!'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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
監聽器將獲得兩個參數,分別標識當前的狀態對象和改變前的狀態對象。
<code>fs<span class="sh_symbol">.</span><span class="sh_function">watchFile</span><span class="sh_symbol">(</span>f<span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>curr<span class="sh_symbol">,</span> prev<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'the current mtime is: '</span> <span class="sh_symbol">+</span> curr<span class="sh_symbol">.</span>mtime<span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'the previous mtime was: '</span> <span class="sh_symbol">+</span> prev<span class="sh_symbol">.</span>mtime<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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 withfs.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
是包含如下默認值的對象:
<code><span class="sh_cbracket">{</span> flags<span class="sh_symbol">:</span> <span class="sh_string">'r'</span><span class="sh_symbol">,</span> encoding<span class="sh_symbol">:</span> <span class="sh_keyword">null</span><span class="sh_symbol">,</span> fd<span class="sh_symbol">:</span> <span class="sh_keyword">null</span><span class="sh_symbol">,</span> mode<span class="sh_symbol">:</span> <span class="sh_number">0666</span><span class="sh_symbol">,</span> bufferSize<span class="sh_symbol">:</span> <span class="sh_number">64</span> <span class="sh_symbol">*</span> <span class="sh_number">1024</span> <span class="sh_cbracket">}</span></code>
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個字節:
<code>fs<span class="sh_symbol">.</span><span class="sh_function">createReadStream</span><span class="sh_symbol">(</span><span class="sh_string">'sample.txt'</span><span class="sh_symbol">,</span> <span class="sh_cbracket">{</span>start<span class="sh_symbol">:</span> <span class="sh_number">90</span><span class="sh_symbol">,</span> end<span class="sh_symbol">:</span> <span class="sh_number">99</span><span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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
參數是包含如下默認值的對象:
<code><span class="sh_cbracket">{</span> flags<span class="sh_symbol">:</span> <span class="sh_string">'w'</span><span class="sh_symbol">,</span> encoding<span class="sh_symbol">:</span> <span class="sh_keyword">null</span><span class="sh_symbol">,</span> mode<span class="sh_symbol">:</span> <span class="sh_number">0666</span> <span class="sh_cbracket">}</span></code>
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:
示例:
<code>path<span class="sh_symbol">.</span><span class="sh_function">normalize</span><span class="sh_symbol">(</span><span class="sh_string">'/foo/bar//baz/asdf/quux/..'</span><span class="sh_symbol">)</span> <span class="sh_comment">// returns</span> <span class="sh_string">'/foo/bar/baz/asdf'</span></code>
path.join([path1], [path2], [...])
Join all arguments together and normalize the resulting path.
該方法用於合併方法中的各參數並得到一個標準化合併的路徑字符串。
Example:
示例:
<code>node<span class="sh_symbol">></span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'path'</span><span class="sh_symbol">).</span><span class="sh_function">join</span><span class="sh_symbol">(</span> <span class="sh_symbol">...</span> <span class="sh_string">'/foo'</span><span class="sh_symbol">,</span> <span class="sh_string">'bar'</span><span class="sh_symbol">,</span> <span class="sh_string">'baz/asdf'</span><span class="sh_symbol">,</span> <span class="sh_string">'quux'</span><span class="sh_symbol">,</span> <span class="sh_string">'..'</span><span class="sh_symbol">)</span> <span class="sh_string">'/foo/bar/baz/asdf'</span></code>
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
命令。
<code>path<span class="sh_symbol">.</span><span class="sh_function">resolve</span><span class="sh_symbol">(</span><span class="sh_string">'foo/bar'</span><span class="sh_symbol">,</span> <span class="sh_string">'/tmp/file/'</span><span class="sh_symbol">,</span> <span class="sh_string">'..'</span><span class="sh_symbol">,</span> <span class="sh_string">'a/../subfile'</span><span class="sh_symbol">)</span></code>
Is similar to:
就類似於:
<code>cd <span class="sh_normal">foo</span><span class="sh_symbol">/</span>bar <span class="sh_normal">cd </span><span class="sh_symbol">/</span><span class="sh_normal">tmp</span><span class="sh_symbol">/</span><span class="sh_normal">file</span><span class="sh_symbol">/</span> cd <span class="sh_symbol">..</span> cd <span class="sh_normal">a</span><span class="sh_symbol">/../</span>subfile pwd</code>
The difference is that the different paths don't need to exist and may also befiles.
該方法與cd
命令的區別在於該方法中不同的路徑不一定存在,而且這些路徑也可能是文件。
Examples:
示例:
<code>path<span class="sh_symbol">.</span><span class="sh_function">resolve</span><span class="sh_symbol">(</span><span class="sh_string">'/foo/bar'</span><span class="sh_symbol">,</span> <span class="sh_string">'./baz'</span><span class="sh_symbol">)</span> <span class="sh_comment">// returns</span> <span class="sh_string">'/foo/bar/baz'</span> path<span class="sh_symbol">.</span><span class="sh_function">resolve</span><span class="sh_symbol">(</span><span class="sh_string">'/foo/bar'</span><span class="sh_symbol">,</span> <span class="sh_string">'/tmp/file/'</span><span class="sh_symbol">)</span> <span class="sh_comment">// returns</span> <span class="sh_string">'/tmp/file'</span> path<span class="sh_symbol">.</span><span class="sh_function">resolve</span><span class="sh_symbol">(</span><span class="sh_string">'wwwroot'</span><span class="sh_symbol">,</span> <span class="sh_string">'static_files/png/'</span><span class="sh_symbol">,</span> <span class="sh_string">'../gif/image.gif'</span><span class="sh_symbol">)</span> <span class="sh_comment">// if currently in /home/myself/node, it returns</span> <span class="sh_string">'/home/myself/node/wwwroot/static_files/gif/image.gif'</span></code>
path.dirname(p)
Return the directory name of a path. Similar to the Unix dirname
command.
該方法返回一個路徑的目錄名,類似於Unix中的dirname
命令。
Example:
示例:
<code>path<span class="sh_symbol">.</span><span class="sh_function">dirname</span><span class="sh_symbol">(</span><span class="sh_string">'/foo/bar/baz/asdf/quux'</span><span class="sh_symbol">)</span> <span class="sh_comment">// returns</span> <span class="sh_string">'/foo/bar/baz/asdf'</span></code>
path.basename(p, [ext])
Return the last portion of a path. Similar to the Unix basename
command.
該方法返回一個路徑中最低一級目錄名,類似於Unix中的 basename
命令。
Example:
示例:
<code>path<span class="sh_symbol">.</span><span class="sh_function">basename</span><span class="sh_symbol">(</span><span class="sh_string">'/foo/bar/baz/asdf/quux.html'</span><span class="sh_symbol">)</span> <span class="sh_comment">// returns</span> <span class="sh_string">'quux.html'</span> path<span class="sh_symbol">.</span><span class="sh_function">basename</span><span class="sh_symbol">(</span><span class="sh_string">'/foo/bar/baz/asdf/quux.html'</span><span class="sh_symbol">,</span> <span class="sh_string">'.html'</span><span class="sh_symbol">)</span> <span class="sh_comment">// returns</span> <span class="sh_string">'quux'</span></code>
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:
示例:
<code>path<span class="sh_symbol">.</span><span class="sh_function">extname</span><span class="sh_symbol">(</span><span class="sh_string">'index.html'</span><span class="sh_symbol">)</span> <span class="sh_comment">// returns</span> <span class="sh_string">'.html'</span> path<span class="sh_symbol">.</span><span class="sh_function">extname</span><span class="sh_symbol">(</span><span class="sh_string">'index'</span><span class="sh_symbol">)</span> <span class="sh_comment">// returns</span> <span class="sh_string">''</span></code>
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
回調函數。示例:
<code>path<span class="sh_symbol">.</span><span class="sh_function">exists</span><span class="sh_symbol">(</span><span class="sh_string">'/etc/passwd'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>exists<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> util<span class="sh_symbol">.</span><span class="sh_function">debug</span><span class="sh_symbol">(</span>exists <span class="sh_symbol">?</span> <span class="sh_string">"it's there"</span> <span class="sh_symbol">:</span> <span class="sh_string">"no passwd!"</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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
onhost
. Ifhost
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
服務器。
<code><span class="sh_keyword">var</span> net <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'net'</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> server <span class="sh_symbol">=</span> net<span class="sh_symbol">.</span><span class="sh_function">createServer</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">(</span>c<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> c<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span><span class="sh_string">'hello</span><span class="sh_specialchar">\r\n</span><span class="sh_string">'</span><span class="sh_symbol">);</span> c<span class="sh_symbol">.</span><span class="sh_function">pipe</span><span class="sh_symbol">(</span>c<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> server<span class="sh_symbol">.</span><span class="sh_function">listen</span><span class="sh_symbol">(</span><span class="sh_number">8124</span><span class="sh_symbol">,</span> <span class="sh_string">'localhost'</span><span class="sh_symbol">);</span></code>
Test this by using telnet
:
使用telnet
測試該服務器。
<code>telnet localhost <span class="sh_number">8124</span></code>
To listen on the socket /tmp/echo.sock
the last line would just bechanged to
如要監聽socket /tmp/echo.sock
,最後一行代碼需要修改成:
<code>server<span class="sh_symbol">.</span><span class="sh_function">listen</span><span class="sh_symbol">(</span><span class="sh_string">'/tmp/echo.sock'</span><span class="sh_symbol">);</span></code>
Use nc
to connect to a UNIX domain socket server:
使用nc
命令連接到一個UNIX域socket服務器:
<code>nc <span class="sh_symbol">-</span><span class="sh_normal">U </span><span class="sh_symbol">/</span><span class="sh_normal">tmp</span><span class="sh_symbol">/</span>echo<span class="sh_symbol">.</span>sock</code>
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
錯誤,該錯誤消息的意思是已經有另一個服務運行在請求的端口上,一個解決方法就是等一會再試一下,就像下面的代碼這樣:
<code>server<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'error'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>e<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>e<span class="sh_symbol">.</span>code <span class="sh_symbol">==</span> <span class="sh_string">'EADDRINUSE'</span><span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Address in use, retrying...'</span><span class="sh_symbol">);</span> <span class="sh_function">setTimeout</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> server<span class="sh_symbol">.</span><span class="sh_function">close</span><span class="sh_symbol">();</span> server<span class="sh_symbol">.</span><span class="sh_function">listen</span><span class="sh_symbol">(</span>PORT<span class="sh_symbol">,</span> HOST<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_number">1000</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
(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:
<code><span class="sh_keyword">var</span> server <span class="sh_symbol">=</span> net<span class="sh_symbol">.</span><span class="sh_function">createServer</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">(</span>socket<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> socket<span class="sh_symbol">.</span><span class="sh_function">end</span><span class="sh_symbol">(</span><span class="sh_string">"goodbye</span><span class="sh_specialchar">\n</span><span class="sh_string">"</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_comment">// grab a random port.</span> server<span class="sh_symbol">.</span><span class="sh_function">listen</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span><span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> address <span class="sh_symbol">=</span> server<span class="sh_symbol">.</span><span class="sh_function">address</span><span class="sh_symbol">();</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"opened server on %j"</span><span class="sh_symbol">,</span> address<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
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
參數是一個對象,默認值如下:
<code><span class="sh_cbracket">{</span> fd<span class="sh_symbol">:</span> <span class="sh_keyword">null</span> type<span class="sh_symbol">:</span> <span class="sh_keyword">null</span> allowHalfOpen<span class="sh_symbol">:</span> <span class="sh_keyword">false</span> <span class="sh_cbracket">}</span></code>
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.
fd
參數允許你指定一個已經存在的socket的文件描述符。type
參數用於指定底層協議,可選值包括'tcp4'
,'tcp6'
或'unix'
。關於allowHalfOpen
,可參考createServer()
和'end'
事件。
socket.connect(port, [host], [callback])
socket.connect(path, [callback])
Opens the connection for a given socket. If port
and host
are given,then the socket will be opened as a TCP socket, ifhost
is omitted,localhost
will be assumed. If a path
is given, the socket
will beopened as a unix socket to that path.
打開一下指定socket的連接。如果給出了port
和 host
,將作爲一個TCP socket打開,如果省略了host
,將默認連接到localhost
。如果指定了path
,該socket將作爲一個UNIX socket打開,並連接到path
路徑。
Normally this method is not needed, as net.createConnection
opens thesocket. Use this only if you are implementing a custom Socket or if aSocket is closed and you want to reuse it to connect to another server.
通常情況下該方法並不需要,使用 net.createConnection
就可以打開socket。只有在你實現一個自定義的socket,或者你想重用一個已經關閉的socket連接到另一個服務器。
This function is asynchronous. When the 'connect'
event is emitted thesocket is established. If there is a problem connecting, the'connect'
event will not be emitted, the 'error'
event will be emitted withthe exception.
這個函數是異步函數。當發生 'connect'
事件時socket被建立,如果連接遇到問題, 'connect'
事件不會被觸發,而攜帶異常信息的'error'
事件將被觸發。
The callback
parameter will be added as an listener for the 'connect'event.
參數callback
將作爲 connect
事件的監聽器被增加進來。
socket.bufferSize
net.Socket
has the property that socket.write()
always works. This is tohelp users get up an running quickly. The computer cannot necessarily keep upwith the amount of data that is written to a socket - the network connection simplymight
be too slow. Node will internally queue up the data written to a socket andsend it out over the wire when it is possible. (Internally it is polling onthe socket's file descriptor for being writable).
net.Socket
有一個特性,那就是socket.write()
隨時可用,這是爲了使程序更快的運行。計算機發送數據的速度可能無法跟上程序向socket寫入數據的速度——考慮網絡速度很慢的情況。Node在內部維護了一個隊列用於保存寫入socket的數據,並在網絡允許的時候將隊列中的數據發送出去。(內部實現是探測socket的文件描述符是否可寫。)
The consequence of this internal buffering is that memory may grow. Thisproperty shows the number of characters currently buffered to be written.(Number of characters is approximately equal to the number of bytes to bewritten, but the buffer may contain strings, and the strings are lazilyencoded, 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 withpause()
and resume()
.
用戶可以在程序中使用pause()
和resume()
來"截流"數據流,以控制大量或不斷增長的bufferSize
。
socket.setEncoding(encoding=null)
Sets the encoding (either 'ascii'
, 'utf8'
, or 'base64'
) for data that isreceived.
設置接收到的數據的編碼(可以是'ascii'
,'utf8'
或'base64'
) 。
socket.setSecure()
This function has been removed in v0.3. It used to upgrade the connection toSSL/TLS. See the TLS for the new API.
該函數用來將連接升級到SSL/TLS,在v0.3版本已經被廢棄。參考TLS中新的API說明。
socket.write(data, [encoding], [callback])
Sends data on the socket. The second parameter specifies the encoding in thecase of a string--it defaults to UTF8 encoding.
向socket發送數據,第二個參數指定在發送字符串數據時的編碼方式,默認的是UTF8編碼。
Returns true
if the entire data was flushed successfully to the kernelbuffer. Returnsfalse
if all or part of the data was queued in user memory.'drain'
will be emitted when the buffer is again free.
在所有數據被成功的寫入系統內核緩衝區時返回true
,如果全部或部分數據進入了用戶內存的隊列則返回false
。當緩衝區再次變空時,'drain'
事件將被觸發。
The optional callback
parameter will be executed when the data is finallywritten out - this may not be immediately.
可選參數callback
將在數據最終被寫出時執行——可能不是立即執行。
socket.write(data, [encoding], [fileDescriptor], [callback])
For UNIX sockets, it is possible to send a file descriptor through thesocket. Simply add thefileDescriptor
argument and listen for the 'fd'
event on the other end.
對於UNIX socket,可以通過socket發送一個文件描述符,簡單的增加參數 fileDescriptor
,並在另一端監聽'fd'
事件。
socket.end([data], [encoding])
Half-closes the socket. I.E., it sends a FIN packet. It is possible theserver will still send some data.
發送一個FIN數據包,關閉socket半連接。服務器仍可能發送一些數據。
If data
is specified, it is equivalent to calling socket.write(data, encoding)
followed bysocket.end()
.
如果指定了data
,等同於依次調用socket.write(data, encoding)
和socket.end()
。
socket.destroy()
Ensures that no more I/O activity happens on this socket. Only necessary incase of errors (parse error or so).
確保該socket上不再有活動的I/O操作,僅在發生錯誤的情況下需要(如解析錯誤等)。
socket.pause()
Pauses the reading of data. That is, 'data'
events will not be emitted.Useful to throttle back an upload.
暫停讀取數據,'data'
將不會被觸發,便於控制上傳速度。
socket.resume()
Resumes reading after a call to pause()
.
用於在調用pause()
後,恢復讀取數據。
socket.setTimeout(timeout, [callback])
Sets the socket to timeout after timeout
milliseconds of inactivity onthe socket. By defaultnet.Socket
do not have a timeout.
設置socket不活動時間超過timeout
毫秒後進入超時狀態。默認情況下net.Socket
不會超時。
When an idle timeout is triggered the socket will receive a 'timeout'
event but the connection will not be severed. The user must manuallyend()
or destroy()
the socket.
當閒置超時發生時,socket會接收到一個'timeout'
事件,但是連接不會被斷開,用戶必須手動的end()
或destroy()
該socket。
If timeout
is 0, then the existing idle timeout is disabled.
如果 timeout
設置成0,已經存在的閒置超時將被禁用。
The optional callback
parameter will be added as a one time listener for the'timeout'
event.
可選參數callback
將作爲一次性監聽器添加到 'timeout'
事件。
socket.setNoDelay(noDelay=true)
Disables the Nagle algorithm. By default TCP connections use the Naglealgorithm, they buffer data before sending it off. SettingnoDelay
willimmediately fire off data each time socket.write()
is called.
禁用Nagle算法。默認情況下TCP連接使用Nagle算法,在發送數據之前緩存它們。設置noDelay
將使每次socket.write()
調用都實時發送數據。
socket.setKeepAlive(enable=false, [initialDelay])
Enable/disable keep-alive functionality, and optionally set the initialdelay before the first keepalive probe is sent on an idle socket.SetinitialDelay
(in milliseconds) to set the delay between the lastdata packet received and the first keepalive
probe. Setting 0 forinitialDelay will leave the value unchanged from the default(or previous) setting.
開啓或禁用keep-alive(連接保持)功能。可選擇設置在一個閒置socket上第一次發送存活探測之前的延遲時間。設置initialDelay
(單位毫秒)以設置最後從一個數據包接收到第一個存活探測發送之間的延時。將initialDelay設爲0將不改變此參數默認(或之前)的設置。
socket.remoteAddress
The string representation of the remote IP address. For example,'74.125.127.100'
or'2001:4860:a005::68'
.
以字符串形式表示的遠端設備IP地址。例如:'74.125.127.100'
或'2001:4860:a005::68'
。
This member is only present in server-side connections.
此成員只存在於服務器端連接中。
Event: 'connect' 事件:'connect'
function () { }
Emitted when a socket connection successfully is established.See connect()
.
當一個socket連接成功建立時觸發,參考 connect()
。
Event: 'data' 事件:'data'
function (data) { }
Emitted when data is received. The argument data
will be a Buffer
orString
. Encoding of data is set bysocket.setEncoding()
.(See the section onReadable Socket
for more information.)
當收到數據時觸發,參數data
將是一個緩衝區(Buffer
)或者字符串(String
)。數據的編碼方式通過socket.setEncoding()
設置。( 更多信息請參考章節Readable Socket
)
Event: 'end' 事件:'end'
function () { }
Emitted when the other end of the socket sends a FIN packet.
當socket的遠端發送了一個FIN數據包時觸發。
By default (allowHalfOpen == false
) the socket will destroy its filedescriptor once it has written out its pending write queue. However, bysettingallowHalfOpen == true
the socket will not automatically end()
its side allowing
the user to write arbitrary amounts of data, with thecaveat that the user is required toend()
their side now.
默認情況下(allowHalfOpen == false
)一旦待寫出隊列中的內容全部被寫出,socket將自動銷燬它的文件描述符。然而如果設置allowHalfOpen == true
,則socket不會自動調用end()
,而是允許用戶繼續寫入任意數量的數據,這種情況下需要用戶主動調用end()
關閉半連接。
Event: 'timeout' 事件:'timeout'
function () { }
Emitted if the socket times out from inactivity. This is only to notify thatthe socket has been idle. The user must manually close the connection.
當socket閒置超時情況下觸發,它只是用來通知那個socket已經空閒,用戶必須手動的關閉該連接。
See also: socket.setTimeout()
參考: socket.setTimeout()
Event: 'drain' 事件:'drain'
function () { }
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
當緩衝區變空時觸發,可以被用來調節上傳速度。
Event: 'error' 事件:'error'
function (exception) { }
Emitted when an error occurs. The 'close'
event will be called directlyfollowing this event.
當有錯誤發生時觸發, 'close'
事件緊跟其後被調用。
Event: 'close' 事件:'close'
function (had_error) { }
Emitted once the socket is fully closed. The argument had_error
is a booleanwhich says if the socket was closed due to a transmission error.
當連接字完全被關閉時觸發,參數had_error
是一個布爾型變量, 用來說明連接字是否由於一個傳輸錯誤而關閉。
net.isIP
net.isIP(input)
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.
測試輸入參數是否是一個IP地址,如果是一個無效的字符串,返回0;如果是IPv4地址,返回4;如果是IPv6地址,返回6。
net.isIPv4(input)
Returns true if input is a version 4 IP address, otherwise returns false.
如果input是一個IPv4地址則返回true,否則返回false。
net.isIPv6(input)
Returns true if input is a version 6 IP address, otherwise returns false.
如果input是一個IPv6地址則返回true,否則返回false。
DNS DNS模塊
Use require('dns')
to access this module.
使用require('dns')
來訪問這個模塊。
Here is an example which resolves 'www.google.com'
then reverseresolves the IP addresses which are returned.
下面這個例子首先將'www.google.com'
解析爲IP地址,再對返回的IP地址做反向解析。
<code><span class="sh_keyword">var</span> dns <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'dns'</span><span class="sh_symbol">);</span> dns<span class="sh_symbol">.</span><span class="sh_function">resolve4</span><span class="sh_symbol">(</span><span class="sh_string">'www.google.com'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">,</span> addresses<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_keyword">throw</span> err<span class="sh_symbol">;</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'addresses: '</span> <span class="sh_symbol">+</span> JSON<span class="sh_symbol">.</span><span class="sh_function">stringify</span><span class="sh_symbol">(</span>addresses<span class="sh_symbol">));</span> addresses<span class="sh_symbol">.</span><span class="sh_function">forEach</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">(</span>a<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> dns<span class="sh_symbol">.</span><span class="sh_function">reverse</span><span class="sh_symbol">(</span>a<span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">,</span> domains<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'reverse for '</span> <span class="sh_symbol">+</span> a <span class="sh_symbol">+</span> <span class="sh_string">' failed: '</span> <span class="sh_symbol">+</span> err<span class="sh_symbol">.</span>message<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span> <span class="sh_keyword">else</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'reverse for '</span> <span class="sh_symbol">+</span> a <span class="sh_symbol">+</span> <span class="sh_string">': '</span> <span class="sh_symbol">+</span> JSON<span class="sh_symbol">.</span><span class="sh_function">stringify</span><span class="sh_symbol">(</span>domains<span class="sh_symbol">));</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
dns.lookup(domain, family=null, callback)
Resolves a domain (e.g. 'google.com'
) into the first found A (IPv4) orAAAA (IPv6) record.
將一個域名(例如'google.com'
)解析成爲找到的第一個A(IPv4)或者AAAA(IPv6)記錄。
The callback has arguments (err, address, family)
. The address
argumentis a string representation of a IP v4 or v6 address. Thefamily
argumentis either the integer 4 or 6 and denotes the family ofaddress
(notnecessarily
the value initially passed to lookup
).
回調函數有(err, address, family)
這三個參數。address
參數是一個代表IPv4或IPv6地址的字符串。family
是一個表示地址版本的整數4或6(並不一定和調用lookup
時傳入的family
參數值相同)。
dns.resolve(domain, rrtype='A', callback)
Resolves a domain (e.g. 'google.com'
) into an array of the record typesspecified by rrtype. Valid rrtypes areA
(IPV4 addresses), AAAA
(IPV6addresses), MX
(mail exchange records),TXT
(text records), SRV
(SRVrecords),
andPTR
(used for reverse IP lookups).
將域名(比如'google.com'
)按照參數rrtype所指定類型的解析結果放到一個數組中。合法的類型爲A
(IPV4地址),AAAA
(IPV6地址),MX
(郵件交換記錄),TXT
(文本記錄),SRV(SRV記錄),和PTR(用於反向IP解析)。
The callback has arguments (err, addresses)
. The type of each iteminaddresses
is determined by the record type, and described in thedocumentation for the corresponding lookup methods below.
回調函數接受兩個參數:(err, addresses)
。參數address
中的每一項的類型根據所要求的記錄類型進行判斷,在下面相應的解析方法的文檔裏有詳細的解釋。
On error, err
would be an instanceof Error
object, whereerr.errno
isone of the error codes listed below anderr.message
is a string describingthe error in English.
當有錯誤發生時,參數err
的內容是一個Error
對象的實例,err.errno
屬性是下面錯誤代碼列表中的一個,err.message
屬性是一個用英語表述的錯誤解釋。
dns.resolve4(domain, callback)
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']
).
與dns.resolve()
類似,但是僅對IPV4地址進行查詢(A
記錄)。addresses
是一個IPV4地址數組(例如['74.125.79.104', '74.125.79.105', '74.125.79.106']
)。
dns.resolve6(domain, callback)
The same as dns.resolve4()
except for IPv6 queries (an AAAA
query).
除了這個函數是對IPV6地址的查詢(一個AAAA
查詢)外與dns.resolve4()
很類似。
dns.resolveMx(domain, callback)
The same as dns.resolve()
, but only for mail exchange queries (MX
records).
與dns.resolve()
很類似,但是僅做郵件交換地址查詢(MX
類型記錄)。
addresses
is an array of MX records, each with a priority and an exchangeattribute (e.g.[{'priority': 10, 'exchange': 'mx.example.com'},...]
).
回調函數的參數addresses
是一個MX類型記錄的數組,每個記錄有一個優先級屬性和一個交換屬性(類似[{'priority': 10, 'exchange': 'mx.example.com'},...]
)。
dns.resolveTxt(domain, callback)
The same as dns.resolve()
, but only for text queries (TXT
records).addresses
is an array of the text records available fordomain
(e.g.,['v=spf1 ip4:0.0.0.0 ~all']
).
與dns.resolve()
很相似,但是僅可以進行文本查詢(TXT
記錄)。addressed
是一個對於domain
域有效的文本記錄數組(類似['v=spf1 ip4:0.0.0.0 ~all']
)。
dns.resolveSrv(domain, callback)
The same as dns.resolve()
, but only for service records (SRV
records).addresses
is an array of the SRV records available fordomain
. Propertiesof SRV records are priority, weight, port, and name (e.g.,[{'priority':
10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]
).
與dns.resolve()
很類似,但僅是隻查詢服務記錄(SRV
類型記錄)。addresses
是一個對於域來說有效的SRV記錄的數組,SRV記錄的屬性有優先級、權重、端口,名字(例如[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]
)。
dns.reverse(ip, callback)
Reverse resolves an ip address to an array of domain names.
反向解析一個IP地址到一個域名數組。
The callback has arguments (err, domains)
.
回調函數的參數爲 (err, domains)
。
If there an an error, err
will be non-null and an instanceof the Errorobject.
如果發生了錯誤,err
將被置爲一個非空的Error對象實例。
Each DNS query can return an error code.
每個DNS查詢可以返回如下錯誤代碼:
-
dns.TEMPFAIL
: timeout, SERVFAIL or similar.dns.TEMPFAIL
: 超時,SERVFAIL或者類似的錯誤。 -
dns.PROTOCOL
: got garbled reply.dns.PROTOCOL
: 返回內容混亂。 -
dns.NXDOMAIN
: domain does not exists.dns.NXDOMAIN
: 域名不存在。 -
dns.NODATA
: domain exists but no data of reqd type.dns.NODATA
: 域名存在但是沒有所請求的查詢類型的數據。 -
dns.NOMEM
: out of memory while processing.dns.NOMEM
: 處理過程中內存溢出。 -
dns.BADQUERY
: the query is malformed.dns.BADQUERY
: 查詢語句語法錯誤。## UDP / Datagram Sockets 數據報套接字模塊
Datagram sockets are available through require('dgram')
. Datagrams are most commonlyhandled as IP/UDP messages but they can also be used over Unix domain sockets.
要使用數據報套接字模塊需要調用require('dgram')
。數據報通常作爲IP/UDP消息來處理,但它也可用於Unix域套接字。
Event: 'message' 事件:'message'
function (msg, rinfo) { }
Emitted when a new datagram is available on a socket. msg
is a Buffer
and rinfo
isan object with the sender's address information and the number of bytes in the datagram.
當套接字接收到一個新的數據報的時候觸發此事件。msg
是一個Buffer
緩衝器,rinfo
是一個包含了發送方地址信息以及數據報字節長度的對象。
Event: 'listening' 事件:'listening'
function () { }
Emitted when a socket starts listening for datagrams. This happens as soon as UDP socketsare created. Unix domain sockets do not start listening until callingbind()
on them.
當一個套接字開始監聽數據報的時候觸發。一旦UDP套接字建立後就會觸發這個事件。而Unix域套接字直到調用了bind()
方法纔會開始監聽。
Event: 'close' 事件:'close'
function () { }
Emitted when a socket is closed with close()
. No new message
events will be emittedon this socket.
當調用close()
方法關閉一個套接字時觸發此事件。此後不會再有新的message
事件在此套接字上發生。
dgram.createSocket(type, [callback])
Creates a datagram socket of the specified types. Valid types are:udp4
,udp6
, and unix_dgram
.
建立一個指定類型的數據報套接字,有效類型有:udp4
,udp6
,以及unix_dgram
。
Takes an optional callback which is added as a listener for message
events.
可選參數callback指定了message
事件的監聽器回調函數。
dgram.send(buf, offset, length, path, [callback])
For Unix domain datagram sockets, the destination address is a pathname in the filesystem.An optional callback may be supplied that is invoked after thesendto
call is completedby the OS. It is not safe to re-use buf
until the callback
is invoked. Note thatunless the socket is bound to a pathname withbind()
there is no way to receive messageson this socket.
對於Unix域數據報套接字而言,目標地址是文件系統中的一個路徑。可選參數callback指定了系統調用sendto
完成後的回調函數。在回調函數callback執行前重複使用buf是很不安全的。要注意除非這個套接字已經使用bind()
方法綁定到一個路徑上,否則這個套接字無法接收到任何信息。
Example of sending a message to syslogd on OSX via Unix domain socket /var/run/syslog
:
一個在OSX系統上,通過Unix域套接字/var/run/syslog
向syslogd發送消息的例子:
<code><span class="sh_keyword">var</span> dgram <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'dgram'</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> message <span class="sh_symbol">=</span> <span class="sh_keyword">new</span> <span class="sh_function">Buffer</span><span class="sh_symbol">(</span><span class="sh_string">"A message to log."</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> client <span class="sh_symbol">=</span> dgram<span class="sh_symbol">.</span><span class="sh_function">createSocket</span><span class="sh_symbol">(</span><span class="sh_string">"unix_dgram"</span><span class="sh_symbol">);</span> client<span class="sh_symbol">.</span><span class="sh_function">send</span><span class="sh_symbol">(</span>message<span class="sh_symbol">,</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> message<span class="sh_symbol">.</span>length<span class="sh_symbol">,</span> <span class="sh_string">"/var/run/syslog"</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">,</span> bytes<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">throw</span> err<span class="sh_symbol">;</span> <span class="sh_cbracket">}</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"Wrote "</span> <span class="sh_symbol">+</span> bytes <span class="sh_symbol">+</span> <span class="sh_string">" bytes to socket."</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
dgram.send(buf, offset, length, port, address, [callback])
For UDP sockets, the destination port and IP address must be specified. A stringmay be supplied for theaddress
parameter, and it will be resolved with DNS. Anoptional callback may be specified to detect any DNS errors and whenbuf
may
bere-used. Note that DNS lookups will delay the time that a send takes place, atleast until the next tick. The only way to know for sure that a send has taken placeis to use the callback.
對於UDP套接字來說,目標端口和IP地址是必須要指定的。可以用字符串來指定address
參數,這個參數通過DNS進行解析。可選參數callback指定一個回調函數,用於檢測DNS解析錯誤以及什麼時候buf
可被重用。注意DNS查詢將會使發送動作最少延遲到下一個時間片執行,如果你想確定發送動作是否發生,使用回調將是唯一的辦法。
Example of sending a UDP packet to a random port on localhost
;
下面是一個發送UDP數據包到localhost
(本機)一個隨機端口的例子:
<code><span class="sh_keyword">var</span> dgram <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'dgram'</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> message <span class="sh_symbol">=</span> <span class="sh_keyword">new</span> <span class="sh_function">Buffer</span><span class="sh_symbol">(</span><span class="sh_string">"Some bytes"</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> client <span class="sh_symbol">=</span> dgram<span class="sh_symbol">.</span><span class="sh_function">createSocket</span><span class="sh_symbol">(</span><span class="sh_string">"udp4"</span><span class="sh_symbol">);</span> client<span class="sh_symbol">.</span><span class="sh_function">send</span><span class="sh_symbol">(</span>message<span class="sh_symbol">,</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> message<span class="sh_symbol">.</span>length<span class="sh_symbol">,</span> <span class="sh_number">41234</span><span class="sh_symbol">,</span> <span class="sh_string">"localhost"</span><span class="sh_symbol">);</span> client<span class="sh_symbol">.</span><span class="sh_function">close</span><span class="sh_symbol">();</span></code>
dgram.bind(path)
For Unix domain datagram sockets, start listening for incoming datagrams on asocket specified bypath
. Note that clients may send()
without bind()
,but no datagrams will be received without abind()
.
對Unix域數據報套接字來說,通過指定一個path
(路徑)開始在套接字上監聽數據報。注意客戶端可以無需調用bind()
直接使用send()
方法發送數據報,但是不使用bind()
方法將無法接收到任何數據報。
Example of a Unix domain datagram server that echoes back all messages it receives:
下面是一個Unix域數據報服務器的例子,此服務器將接收到的所有消息原樣返回:
<code><span class="sh_keyword">var</span> dgram <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">"dgram"</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> serverPath <span class="sh_symbol">=</span> <span class="sh_string">"/tmp/dgram_server_sock"</span><span class="sh_symbol">;</span> <span class="sh_keyword">var</span> server <span class="sh_symbol">=</span> dgram<span class="sh_symbol">.</span><span class="sh_function">createSocket</span><span class="sh_symbol">(</span><span class="sh_string">"unix_dgram"</span><span class="sh_symbol">);</span> server<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">"message"</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>msg<span class="sh_symbol">,</span> rinfo<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"got: "</span> <span class="sh_symbol">+</span> msg <span class="sh_symbol">+</span> <span class="sh_string">" from "</span> <span class="sh_symbol">+</span> rinfo<span class="sh_symbol">.</span>address<span class="sh_symbol">);</span> server<span class="sh_symbol">.</span><span class="sh_function">send</span><span class="sh_symbol">(</span>msg<span class="sh_symbol">,</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> msg<span class="sh_symbol">.</span>length<span class="sh_symbol">,</span> rinfo<span class="sh_symbol">.</span>address<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> server<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">"listening"</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"server listening "</span> <span class="sh_symbol">+</span> server<span class="sh_symbol">.</span><span class="sh_function">address</span><span class="sh_symbol">().</span>address<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">)</span> server<span class="sh_symbol">.</span><span class="sh_function">bind</span><span class="sh_symbol">(</span>serverPath<span class="sh_symbol">);</span></code>
Example of a Unix domain datagram client that talks to this server:
下面是一個與上述服務器通信的Unix域數據報客戶端的例子:
<code><span class="sh_keyword">var</span> dgram <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">"dgram"</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> serverPath <span class="sh_symbol">=</span> <span class="sh_string">"/tmp/dgram_server_sock"</span><span class="sh_symbol">;</span> <span class="sh_keyword">var</span> clientPath <span class="sh_symbol">=</span> <span class="sh_string">"/tmp/dgram_client_sock"</span><span class="sh_symbol">;</span> <span class="sh_keyword">var</span> message <span class="sh_symbol">=</span> <span class="sh_keyword">new</span> <span class="sh_function">Buffer</span><span class="sh_symbol">(</span><span class="sh_string">"A message at "</span> <span class="sh_symbol">+</span> <span class="sh_symbol">(</span><span class="sh_keyword">new</span> <span class="sh_predef_func">Date</span><span class="sh_symbol">()));</span> <span class="sh_keyword">var</span> client <span class="sh_symbol">=</span> dgram<span class="sh_symbol">.</span><span class="sh_function">createSocket</span><span class="sh_symbol">(</span><span class="sh_string">"unix_dgram"</span><span class="sh_symbol">);</span> client<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">"message"</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>msg<span class="sh_symbol">,</span> rinfo<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"got: "</span> <span class="sh_symbol">+</span> msg <span class="sh_symbol">+</span> <span class="sh_string">" from "</span> <span class="sh_symbol">+</span> rinfo<span class="sh_symbol">.</span>address<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> client<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">"listening"</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"client listening "</span> <span class="sh_symbol">+</span> client<span class="sh_symbol">.</span><span class="sh_function">address</span><span class="sh_symbol">().</span>address<span class="sh_symbol">);</span> client<span class="sh_symbol">.</span><span class="sh_function">send</span><span class="sh_symbol">(</span>message<span class="sh_symbol">,</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> message<span class="sh_symbol">.</span>length<span class="sh_symbol">,</span> serverPath<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> client<span class="sh_symbol">.</span><span class="sh_function">bind</span><span class="sh_symbol">(</span>clientPath<span class="sh_symbol">);</span></code>
dgram.bind(port, [address])
For UDP sockets, listen for datagrams on a named port
and optionaladdress
. Ifaddress
is not specified, the OS will try to listen on all addresses.
對於UDP套接字而言,該方法會在port
指定的端口和可選地址 address
上監聽數據報。如果address
沒有指定,則操作系統會監聽所有有效地址。
Example of a UDP server listening on port 41234:
下面是一個監聽在41234端口的UDP服務器的例子:
<code><span class="sh_keyword">var</span> dgram <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">"dgram"</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> server <span class="sh_symbol">=</span> dgram<span class="sh_symbol">.</span><span class="sh_function">createSocket</span><span class="sh_symbol">(</span><span class="sh_string">"udp4"</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> messageToSend <span class="sh_symbol">=</span> <span class="sh_keyword">new</span> <span class="sh_function">Buffer</span><span class="sh_symbol">(</span><span class="sh_string">"A message to send"</span><span class="sh_symbol">);</span> server<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">"message"</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>msg<span class="sh_symbol">,</span> rinfo<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"server got: "</span> <span class="sh_symbol">+</span> msg <span class="sh_symbol">+</span> <span class="sh_string">" from "</span> <span class="sh_symbol">+</span> rinfo<span class="sh_symbol">.</span>address <span class="sh_symbol">+</span> <span class="sh_string">":"</span> <span class="sh_symbol">+</span> rinfo<span class="sh_symbol">.</span>port<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> server<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">"listening"</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">var</span> address <span class="sh_symbol">=</span> server<span class="sh_symbol">.</span><span class="sh_function">address</span><span class="sh_symbol">();</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"server listening "</span> <span class="sh_symbol">+</span> address<span class="sh_symbol">.</span>address <span class="sh_symbol">+</span> <span class="sh_string">":"</span> <span class="sh_symbol">+</span> address<span class="sh_symbol">.</span>port<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> server<span class="sh_symbol">.</span><span class="sh_function">bind</span><span class="sh_symbol">(</span><span class="sh_number">41234</span><span class="sh_symbol">);</span> <span class="sh_comment">// server listening 0.0.0.0:41234</span></code>
dgram.close()
Close the underlying socket and stop listening for data on it. UDP socketsautomatically listen for messages, even if they did not callbind()
.
該函數關閉底層的套接字並停止在其上監聽數據。UDP套接字在沒有調用bing()
方法的情況下也自動監聽消息。
dgram.address()
Returns an object containing the address information for a socket. For UDP sockets,this object will containaddress
and port
. For Unix domain sockets, it will containonlyaddress
.
返回包含套接字地址信息的對象。對於UDP套接字來說,這個對象將包含address
(地址)和port
(端口)。對於UNIX域套接字來說,這個對象僅包含address
(地址)。
dgram.setBroadcast(flag)
Sets or clears the SO_BROADCAST
socket option. When this option is set, UDP packetsmay be sent to a local interface's broadcast address.
設置或者清除套接字的SO_BROADCAST
(廣播)選項。當該設置生效時,UDP數據包將被髮送至本地網絡接口的廣播地址。
dgram.setTTL(ttl)
Sets the IP_TTL
socket option. TTL stands for "Time to Live," but in this context itspecifies the number of IP hops that a packet is allowed to go through. Each router orgateway that forwards a packet decrements the TTL. If the TTL is decremented
to 0 by arouter, it will not be forwarded. Changing TTL values is typically done for networkprobes or when multicasting.
設置套接字的IP_TTL
選項,TTL表示“存活時間”,但是在這個上下文環境中,特指一個數據包允許經過的IP跳數。每經過一個路由器或者網關TTL的值都會減一,如果TTL被一個路由器減少到0,這個數據包將不會繼續轉發。在網絡探針或組播應用中會需要修改TTL數值。
The argument to setTTL()
is a number of hops between 1 and 255. The default on mostsystems is 64.
在setTTL()
調用中設置的跳數介於1到255之間,大多數系統缺省會設置爲64。
dgram.setMulticastTTL(ttl)
Sets the IP_MULTICAST_TTL
socket option. TTL stands for "Time to Live," but in thiscontext 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 packetdecrements
the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
設置套接字的IP_MULTICAST_TTL
選項。TTL全稱"Time to Live",原指存活時間,但在這裏特指在組播通信中數據包允許經過的IP跳數。每經過一個路由器或者網關TTL的值都會減一。如果TTL被一個路由器減少到0,那麼該數據包將不會繼續傳播。
The argument to setMulticastTTL()
is a number of hops between 0 and 255. The default on mostsystems is 64.
setMulticastTTL()
的參數爲1至255之間的跳數,大部分操作系統的默認值爲64。
dgram.setMulticastLoopback(flag)
Sets or clears the IP_MULTICAST_LOOP
socket option. When this option is set, multicastpackets will also be received on the local interface.
設置或清除套接字的IP_MULTICAST_LOOP
選項。當該選項生效時,多路傳播的數據包也會被本地網絡接口接收到。
dgram.addMembership(multicastAddress, [multicastInterface])
Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP
socket option.
該方法通知系統內核使用IP_ADD_MEMBERSHIP
套接字選項將套接字加入一個組播組。
If multicastAddress
is not specified, the OS will try to add membership to all validinterfaces.
如果沒有指定multicastInterface
參數,操作系統將嘗試把所有有效的網絡接口加入組播組。
dgram.dropMembership(multicastAddress, [multicastInterface])
Opposite of addMembership
- tells the kernel to leave a multicast group withIP_DROP_MEMBERSHIP
socket option. This is automatically called by the kernelwhen the socket is closed or process terminates, so most apps will never need to
callthis.
與addMembership
相反,該方法通知系統內核使用IP_DROP_MEMBERSHIP
選項使套接字脫離組播組。由於當套接字關閉或進程終止時該操作會自動執行,所以大部分的應用不需要手動調用該方法。
If multicastAddress
is not specified, the OS will try to drop membership to all validinterfaces.
如果multicastInterface
沒有指定,操作系統會嘗試將所有可用網絡接口從組播組裏脫離。
HTTP HTTP模塊
To use the HTTP server and client one must require('http')
.
如果要使用HTTP的服務器以及客戶端,需使用require('http')
加載HTTP模塊。
The HTTP interfaces in Node are designed to support many featuresof the protocol which have been traditionally difficult to use.In particular, large, possibly chunk-encoded, messages. The interface iscareful to never buffer entire requests or responses--theuser is able to stream data.
Node中的HTTP接口在設計時就考慮到了要支持HTTP協議的很多特性,並且使用簡單。特別是可以處理那些內容龐大,有可能是塊編碼的消息。該接口被設計爲從不緩衝整個請求或相應,這樣用戶就可以以流的方式處理數據。
HTTP message headers are represented by an object like this:
HTTP頭信息以如下對象形式表示:
<code><span class="sh_cbracket">{</span> <span class="sh_string">'content-length'</span><span class="sh_symbol">:</span> <span class="sh_string">'123'</span><span class="sh_symbol">,</span> <span class="sh_string">'content-type'</span><span class="sh_symbol">:</span> <span class="sh_string">'text/plain'</span><span class="sh_symbol">,</span> <span class="sh_string">'connection'</span><span class="sh_symbol">:</span> <span class="sh_string">'keep-alive'</span><span class="sh_symbol">,</span> <span class="sh_string">'accept'</span><span class="sh_symbol">:</span> <span class="sh_string">'*/*'</span> <span class="sh_cbracket">}</span></code>
Keys are lowercased. Values are not modified.
所有鍵名被轉爲小寫,而值不會被修改。
In order to support the full spectrum of possible HTTP applications, Node'sHTTP API is very low-level. It deals with stream handling and messageparsing only. It parses a message into headers and body but it does notparse the actual headers or the body.
爲了支持儘可能多的HTTP應用,Node提供非常底層的HTTP API。它只處理流相關的操作以及進行信息解析。API將信息解析爲頭部和正文,但並不解析實際的頭部和正文內的具體內容。
http.Server
This is an EventEmitter
with the following events:
這是一個帶有如下事件的EventEmitter
事件觸發器:
Event: 'request' 事件:'request'
function (request, response) { }
request
is an instance of http.ServerRequest
and response
is an instance of http.ServerResponse
request
是http.ServerRequest
的一個實例,而response
是http.ServerResponse
的一個實例。
Event: 'connection' 事件:'connection'
function (stream) { }
When a new TCP stream is established. stream
is an object of typenet.Stream
. Usually users will not want to access this event. The stream
can also be accessed at request.connection
.
當一個新的TCP流建立後觸發此事件。stream
是一個net.Stream
類型的對象,通常用戶不會使用這個事件。參數stream
也可以在request.connection
中獲得。
Event: 'close' 事件:'close'
function (errno) { }
Emitted when the server closes.
當服務器關閉的時候觸發此事件。
Event: 'request' 事件:'request'
function (request, response) {}
Emitted each time there is request. Note that there may be multiple requestsper connection (in the case of keep-alive connections).
每個請求發生的時候均會被觸發。請注意每個連接可能會有多個請求(在keep-alive連接情況下)。
Event: 'checkContinue' 事件:'checkContinue'
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 respondwith a 100 Continue as appropriate.
每當帶有Exception: 100-continue頭的請求被接收到時觸發此事件。如果該事件未被監聽,服務器會視情況自動的使用100 Continue應答。
Handling this event involves calling response.writeContinue
if the clientshould continue to send the request body, or generating an appropriate HTTPresponse (e.g., 400 Bad Request) if the client should not continue to send therequest body.
該事件的處理涉及兩種情況,如果客戶端應當繼續發送請求正文,那麼需要調用response.writeContinue
,而如果客戶端不應該繼續發送請求正文,那麼應該產生一個適當的HTTP迴應(如400錯誤請求)。
Note that when this event is emitted and handled, the request
event willnot be emitted.
注意如果該事件被觸發並處理的話,那麼將不再觸發request
事件。
Event: 'upgrade' 事件:'upgrade'
function (request, socket, head)
Emitted each time a client requests a http upgrade. If this event isn'tlistened for, then clients requesting an upgrade will have their connectionsclosed.
每當一個客戶端請求http upgrade時觸發此消息。如果這個事件沒有監聽,那麼請求upgrade的客戶端的連接將被關閉。
-
request
is the arguments for the http request, as it is in the request event.request
代表一個http請求的相關參數,和它在request事件中的意思相同。 -
socket
is the network socket between the server and client.socket
是在服務器與客戶端之間連接使用的網絡套接字。 -
head
is an instance of Buffer, the first packet of the upgraded stream, this may be empty.head
是一個緩衝器實例,是upgraded流的第一個包,這個緩衝器可以是空的。
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 datasent to the server on that socket.
當此事件被觸發後,該請求所使用的套接字將不會有一個data
事件監聽器。這意味着你如果需要處理通過這個套接字發送到服務器端的數據則需要自己綁定data
事件監聽器。
Event: 'clientError' 事件:'clientError'
function (exception) {}
If a client connection emits an 'error' event - it will forwarded here.
當客戶端連接出現錯誤時會觸發'error'事件。
http.createServer(requestListener)
Returns a new web server object.
返回一個新的web server對象。
The requestListener
is a function which is automaticallyadded to the'request'
event.
requestListener監聽器會自動添加到'request'
事件中。
server.listen(port, [hostname], [callback])
Begin accepting connections on the specified port and hostname. If thehostname is omitted, the server will accept connections directed to anyIPv4 address (INADDR_ANY
).
在指定端口和主機名上接受連接。如果hostname沒有指定,服務器將直接在此機器的所有IPV4地址上接受連接(INADDR_ANY
)。
To listen to a unix socket, supply a filename instead of port and hostname.
如果要在UNIX套接字上監聽的話,則需要提供一個文件名來替換端口和主機名。
This function is asynchronous. The last parameter callback
will be calledwhen the server has been bound to the port.
這個方法是一個異步的方法,當服務器已經在此端口上完成綁定後講調用callback
回調函數。
server.listen(path, [callback])
Start a UNIX socket server listening for connections on the given path
.
建立一個UNIX套接字服務器並在指定path
路徑上監聽。
This function is asynchronous. The last parameter callback
will be calledwhen the server has been bound.
這個方法是一個異步的方法,當服務器完成綁定後將調用callback
回調函數。
server.close()
Stops the server from accepting new connections.
使此服務器停止接受任何新連接。
http.ServerRequest
This object is created internally by a HTTP server -- not bythe user -- and passed as the first argument to a'request'
listener.
這個對象通常由HTTP服務器(而非用戶)自動建立,並作爲第一個參數傳給'request'
監聽器。
This is an EventEmitter
with the following events:
這是一個帶有如下事件的EventEmitter
事件觸發器:
Event: 'data' 事件:'data'
function (chunk) { }
Emitted when a piece of the message body is received.
當接收到信息正文中的一部分時候會觸發此事件。
Example: A chunk of the body is given as the singleargument. The transfer-encoding has been decoded. Thebody chunk is a string. The body encoding is set withrequest.setBodyEncoding()
.
例如:正文的數據塊將作爲唯一的參數傳遞給回調函數。此時傳輸編碼已被解碼。正文數據塊是一個字符串,正文的編碼由request.setBodyEncoding()
方法設定。
Event: 'end' 事件:'end'
function () { }
Emitted exactly once for each message. No arguments. Afteremitted no other events will be emitted on the request.
每次完全接收完信息後都會觸發一次,不接受任何參數。當這個事件被觸發後,將不會再觸發其他事件。
request.method
The request method as a string. Read only. Example:'GET'
, 'DELETE'
.
表示請求方式的只讀字符串。例如'GET'
,'DELETE'
。
request.url
Request URL string. This contains only the URL that ispresent in the actual HTTP request. If the request is:
代表所請求URL的字符串。他僅包括實際的HTTP請求中的URL地址。如果這個請求是:
<code><span class="sh_normal">GET </span><span class="sh_symbol">/</span>status<span class="sh_symbol">?</span>name<span class="sh_symbol">=</span>ryan <span class="sh_normal">HTTP</span><span class="sh_symbol">/</span><span class="sh_number">1.1</span><span class="sh_symbol">\</span>r<span class="sh_symbol">\</span>n Accept<span class="sh_symbol">:</span> <span class="sh_normal">text</span><span class="sh_symbol">/</span>plain<span class="sh_symbol">\</span>r<span class="sh_symbol">\</span>n <span class="sh_symbol">\</span>r<span class="sh_symbol">\</span>n</code>
Then request.url
will be:
則request.url
應當是:
<code>'/status?name=ryan'</code>
If you would like to parse the URL into its parts, you can userequire('url').parse(request.url)
. Example:
如果你想要解析這個URL中的各個部分,可以使用require('url').parse(request.url)
。例如:
<code>node<span class="sh_symbol">></span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'url'</span><span class="sh_symbol">).</span><span class="sh_function">parse</span><span class="sh_symbol">(</span><span class="sh_string">'/status?name=ryan'</span><span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> href<span class="sh_symbol">:</span> <span class="sh_string">'/status?name=ryan'</span><span class="sh_symbol">,</span> search<span class="sh_symbol">:</span> <span class="sh_string">'?name=ryan'</span><span class="sh_symbol">,</span> query<span class="sh_symbol">:</span> <span class="sh_string">'name=ryan'</span><span class="sh_symbol">,</span> pathname<span class="sh_symbol">:</span> <span class="sh_string">'/status'</span> <span class="sh_cbracket">}</span></code>
If you would like to extract the params from the query string,you can use the require('querystring').parse
function, or passtrue
as the second argument torequire('url').parse
. Example:
如果你想從查詢字符串中提取所有參數,你可以使用require('querystring').parse
方法,或者傳一個true
作爲第二個參數給require('url').parse
方法。例如:
<code>node<span class="sh_symbol">></span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'url'</span><span class="sh_symbol">).</span><span class="sh_function">parse</span><span class="sh_symbol">(</span><span class="sh_string">'/status?name=ryan'</span><span class="sh_symbol">,</span> <span class="sh_keyword">true</span><span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> href<span class="sh_symbol">:</span> <span class="sh_string">'/status?name=ryan'</span><span class="sh_symbol">,</span> search<span class="sh_symbol">:</span> <span class="sh_string">'?name=ryan'</span><span class="sh_symbol">,</span> query<span class="sh_symbol">:</span> <span class="sh_cbracket">{</span> name<span class="sh_symbol">:</span> <span class="sh_string">'ryan'</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> pathname<span class="sh_symbol">:</span> <span class="sh_string">'/status'</span> <span class="sh_cbracket">}</span></code>
request.headers
Read only.
只讀。
request.trailers
Read only; HTTP trailers (if present). Only populated after the 'end' event.
只讀,HTTP尾部(如果存在的話),只有在'end'事件被觸發後該值纔會被填充。
request.httpVersion
The HTTP protocol version as a string. Read only. Examples:'1.1'
,'1.0'
.Also request.httpVersionMajor
is the first integer andrequest.httpVersionMinor
is the second.
只讀的,以字符串形式表示HTTP協議版本。例如'1.1'
,'1.0'
。request.httpVersionMajor
對應版本號的第一個數字,request.httpVersionMinor
則對應第二個數字。
request.setEncoding(encoding=null)
Set the encoding for the request body. Either 'utf8'
or 'binary'
. Defaultstonull
, which means that the 'data'
event will emit a Buffer
object..
設置此請求正文的字符編碼,'utf8'
或者'binary'
。缺省值是null
,這表示'data'
事件的參數將會是一個緩衝器對象。
request.pause()
Pauses request from emitting events. Useful to throttle back an upload.
暫停此請求的事件觸發。對於控制上傳非常有用。
request.resume()
Resumes a paused request.
恢復一個暫停的請求。
request.connection
The net.Stream
object associated with the connection.
與當前連接相關聯的net.Stream
對象。
With HTTPS support, use request.connection.verifyPeer() andrequest.connection.getPeerCertificate() to obtain the client'sauthentication details.
對於使用HTTPS的連接,可使用request.connection.verifyPeer()和request.connection.getPeerCertificate()來獲得客戶端的認證詳情。
http.ServerResponse
This object is created internally by a HTTP server--not by the user. It ispassed as the second parameter to the'request'
event. It is a Writable Stream
.
這個對象由HTTP服務器(而非用戶)自動建立。它作爲'request'
事件的第二個參數,這是一個Writable Stream
可寫流。
response.writeContinue()
Sends a HTTP/1.1 100 Continue message to the client, indicating thatthe request body should be sent. See the thecheckContinue
event onServer
.
發送HTTP/1.1 100 Continue消息給客戶端,通知客戶端可以發送請求的正文。參見服務器Server
中的checkContinue
事件。
response.writeHead(statusCode, [reasonPhrase], [headers])
Sends a response header to the request. The status code is a 3-digit HTTPstatus code, like404
. The last argument, headers
, are the response headers.Optionally one can give a human-readablereasonPhrase
as the secondargument.
這個方法用來發送一個響應頭,statusCode是一個由3位數字所構成的HTTP狀態碼,比如404
之類。最後一個參數headers
是響應頭具體內容。也可以使用一個方便人們直觀理解的reasonPhrase
作爲第二個參數。
Example:
<code><span class="sh_keyword">var</span> body <span class="sh_symbol">=</span> <span class="sh_string">'hello world'</span><span class="sh_symbol">;</span> response<span class="sh_symbol">.</span><span class="sh_function">writeHead</span><span class="sh_symbol">(</span><span class="sh_number">200</span><span class="sh_symbol">,</span> <span class="sh_cbracket">{</span> <span class="sh_string">'Content-Length'</span><span class="sh_symbol">:</span> body<span class="sh_symbol">.</span>length<span class="sh_symbol">,</span> <span class="sh_string">'Content-Type'</span><span class="sh_symbol">:</span> <span class="sh_string">'text/plain'</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
This method must only be called once on a message and it mustbe called before response.end()
is called.
在一次請求響應中此方法只能調用一次,並且必須在調用response.end()
之前調用。
If you call response.write()
or response.end()
before calling this, theimplicit/mutable headers will be calculated and call this function for you.
如果你在response.write()
或者response.end()
之後調用此方法,響應頭的內容將是不確定而且不可知的。
response.statusCode
When using implicit headers (not calling response.writeHead()
explicitly), this propertycontrols the status code that will be send to the client when the headers getflushed.
當隱式的發送響應頭信息(沒有明確調用response.writeHead()
)時,使用此屬性將設置返回給客戶端的狀態碼。狀態嗎將在響應頭信息發送時一起被髮送。
Example:
例如:
<code>response<span class="sh_symbol">.</span>statusCode <span class="sh_symbol">=</span> <span class="sh_number">404</span><span class="sh_symbol">;</span></code>
response.setHeader(name, value)
Sets a single header value for implicit headers. If this header already existsin the to-be-sent headers, it's value will be replaced. Use an array of stringshere if you need to send multiple headers with the same name.
在隱式的響應頭基礎上設置單個頭信息。如果存在同名的待發送頭信息,那麼該頭信息的值將被替換。如果你想發送相同名字的多個頭部信息,可以使用字符串數組的形式設置。
Example:
例如:
<code>response<span class="sh_symbol">.</span><span class="sh_function">setHeader</span><span class="sh_symbol">(</span><span class="sh_string">"Content-Type"</span><span class="sh_symbol">,</span> <span class="sh_string">"text/html"</span><span class="sh_symbol">);</span></code>
或者
<code>response<span class="sh_symbol">.</span><span class="sh_function">setHeader</span><span class="sh_symbol">(</span><span class="sh_string">"Set-Cookie"</span><span class="sh_symbol">,</span> <span class="sh_symbol">[</span><span class="sh_string">"type=ninja"</span><span class="sh_symbol">,</span> <span class="sh_string">"language=javascript"</span><span class="sh_symbol">]);</span></code>
response.getHeader(name)
Reads out a header that's already been queued but not sent to the client. Notethat the name is case insensitive. This can only be called before headers getimplicitly flushed.
讀取已經排列好但尚未發送給客戶端的頭部信息,注意參數名不區分大小寫。此方法必須在響應頭信息隱式發送之前調用。
Example:
例如:
<code><span class="sh_keyword">var</span> contentType <span class="sh_symbol">=</span> response<span class="sh_symbol">.</span><span class="sh_function">getHeader</span><span class="sh_symbol">(</span><span class="sh_string">'content-type'</span><span class="sh_symbol">);</span></code>
response.removeHeader(name)
Removes a header that's queued for implicit sending.
移除等待隱式發送的頭部信息。
Example:
例如:
<code>response<span class="sh_symbol">.</span><span class="sh_function">removeHeader</span><span class="sh_symbol">(</span><span class="sh_string">"Content-Encoding"</span><span class="sh_symbol">);</span></code>
response.write(chunk, encoding='utf8')
If this method is called and response.writeHead()
has not been called, it willswitch to implicit header mode and flush the implicit headers.
如果在response.writeHead()
調用之前調用該函數,將會切換到隱式發送響應頭信息的模式併發送隱式的頭部信息。
This sends a chunk of the response body. This method maybe 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 theencoding
is 'utf8'
.
chunk
可以是一個字符串或者一個緩衝器。如果chunk
是一個字符串,則第二個參數指定用何種編碼方式將字符串編碼爲字節流。缺省情況下,encoding
爲'utf8'
。
Note: This is the raw HTTP body and has nothing to do withhigher-level multi-part body encodings that may be used.
注意:這是一個原始格式HTTP正文,和高層協議中的多段正文編碼格式無關。
The first time response.write()
is called, it will send the bufferedheader information and the first body to the client. The second timeresponse.write()
is called, Node assumes you're going to be streamingdata, and sends that separately.
That is, the response is buffered up to thefirst chunk of body.
第一次調用response.write()
時,此方法會將已經緩衝的消息頭和第一塊正文發送給客戶。 當第二次調用response.write()
的時候,Node將假定你想要逐次發送流數據。換句話說,響應被緩衝直到正文的第一塊被髮送。
response.addTrailers(headers)
This method adds HTTP trailing headers (a header but at the end of themessage) to the response.
該方法在響應中添加HTTP尾部頭信息(在消息尾部的頭信息)。
Trailers will only be emitted if chunked encoding is used for theresponse; if it is not (e.g., if the request was HTTP/1.0), they willbe silently discarded.
僅當響應報文使用chunked編碼時,尾部信息纔會發送;否則(例如請求的協議版本爲HTTP/1.0)它們會被拋棄而沒有提示。
Note that HTTP requires the Trailer
header to be sent if you intend toemit trailers, with a list of the header fields in its value. E.g.,
注意如果你想發送尾部信息,則需要在HTTP頭中添加Trailer
。
<code>response<span class="sh_symbol">.</span><span class="sh_function">writeHead</span><span class="sh_symbol">(</span><span class="sh_number">200</span><span class="sh_symbol">,</span> <span class="sh_cbracket">{</span> <span class="sh_string">'Content-Type'</span><span class="sh_symbol">:</span> <span class="sh_string">'text/plain'</span><span class="sh_symbol">,</span> <span class="sh_string">'Trailer'</span><span class="sh_symbol">:</span> <span class="sh_string">'TraceInfo'</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> response<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span>fileData<span class="sh_symbol">);</span> response<span class="sh_symbol">.</span><span class="sh_function">addTrailers</span><span class="sh_symbol">(</span><span class="sh_cbracket">{</span><span class="sh_string">'Content-MD5'</span><span class="sh_symbol">:</span> <span class="sh_string">"7895bf4b8828b55ceaf47747b4bca667"</span><span class="sh_cbracket">}</span><span class="sh_symbol">);</span> response<span class="sh_symbol">.</span><span class="sh_function">end</span><span class="sh_symbol">();</span></code>
response.end([data], [encoding])
This method signals to the server that all of the response headers and bodyhas been sent; that server should consider this message complete.The method,response.end()
, MUST be called on eachresponse.
這個方法通知服務器所有的響應頭和響應正文都已經發出;服務器在此調用後認爲這條信息已經發送完畢。在每個響應上都必須調用response.end()
方法。
If data
is specified, it is equivalent to calling response.write(data, encoding)
followed byresponse.end()
.
如果指定了data
參數,就相當先調用response.write(data, encoding)
再調用response.end()
。
http.request(options, callback)
Node maintains several connections per server to make HTTP requests.This function allows one to transparently issue requests.
Node爲一個目標服務器維護多個連接用於HTTP請求。通過這個方法可以向服務器發送請求。
Options:
選項:
-
host
: A domain name or IP address of the server to issue the request to.host
: 請求的服務器域名或者IP地址。 -
port
: Port of remote server.port
: 遠端服務器的端口。 -
method
: A string specifying the HTTP request method. Possible values:'GET'
(default),'POST'
,'PUT'
, and'DELETE'
.method
: 指定HTTP請求的方法類型,可選的值有:'GET'
(默認),'POST'
,'PUT'
,以及'DELETE'
。 -
path
: Request path. Should include query string and fragments if any.E.G.'/index.html?page=12'
path
: 請求地址,可包含查詢字符串以及可能存在的錨點。例如'/index.html?page=12'
。 -
headers
: An object containing request headers.headers
: 一個包含請求頭的對象。
http.request()
returns an instance of the http.ClientRequest
class. TheClientRequest
instance is a writable stream. If one needs toupload a file with a POST request, then write to theClientRequest
object.
http.request()
函數返回http.ClientRequest
類的一個實例。ClientRequest
對象是一個可寫流,如果你需要用POST方法上傳一個文件,可將其寫入到ClientRequest
對象中。
Example:
例子:
<code><span class="sh_keyword">var</span> options <span class="sh_symbol">=</span> <span class="sh_cbracket">{</span> host<span class="sh_symbol">:</span> <span class="sh_string">'www.google.com'</span><span class="sh_symbol">,</span> port<span class="sh_symbol">:</span> <span class="sh_number">80</span><span class="sh_symbol">,</span> path<span class="sh_symbol">:</span> <span class="sh_string">'/upload'</span><span class="sh_symbol">,</span> method<span class="sh_symbol">:</span> <span class="sh_string">'POST'</span> <span class="sh_cbracket">}</span><span class="sh_symbol">;</span> <span class="sh_keyword">var</span> req <span class="sh_symbol">=</span> http<span class="sh_symbol">.</span><span class="sh_function">request</span><span class="sh_symbol">(</span>options<span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>res<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'STATUS: '</span> <span class="sh_symbol">+</span> res<span class="sh_symbol">.</span>statusCode<span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'HEADERS: '</span> <span class="sh_symbol">+</span> JSON<span class="sh_symbol">.</span><span class="sh_function">stringify</span><span class="sh_symbol">(</span>res<span class="sh_symbol">.</span>headers<span class="sh_symbol">));</span> res<span class="sh_symbol">.</span><span class="sh_function">setEncoding</span><span class="sh_symbol">(</span><span class="sh_string">'utf8'</span><span class="sh_symbol">);</span> res<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>chunk<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'BODY: '</span> <span class="sh_symbol">+</span> chunk<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_comment">// write data to request body</span> req<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span><span class="sh_string">'data</span><span class="sh_specialchar">\n</span><span class="sh_string">'</span><span class="sh_symbol">);</span> req<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span><span class="sh_string">'data</span><span class="sh_specialchar">\n</span><span class="sh_string">'</span><span class="sh_symbol">);</span> req<span class="sh_symbol">.</span><span class="sh_function">end</span><span class="sh_symbol">();</span></code>
Note that in the example req.end()
was called. With http.request()
onemust always callreq.end()
to signify that you're done with the request -even if there is no data being written to the request body.
注意這個例子中req.end()
被調用了。無論請求正文是否包含數據,每一次調用http.request()
最後都需要調用一次req.end()
表示已經完成了請求。
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 emittedon the returned request object.
如果在請求過程中出現了錯誤(可能是DNS解析、TCP的錯誤、或者HTTP解析錯誤),返回的請求對象上的'error'
的事件將被觸發。
There are a few special headers that should be noted.
如下特別的消息頭應當注意:
-
Sending a 'Connection: keep-alive' will notify Node that the connection tothe server should be persisted until the next request.
發送'Connection: keep-alive'頭部將通知Node此連接將保持到下一此請求。
-
Sending a 'Content-length' header will disable the default chunked encoding.
發送'Content-length'頭將使默認的分塊編碼無效。
-
Sending an 'Expect' header will immediately send the request headers.Usually, when sending 'Expect: 100-continue', you should both set a timeoutand listen for the
continue
event. See RFC2616 Section 8.2.3 for moreinformation.發送'Expect'頭部將引起請求頭部立即被髮送。通常情況,當發送'Expect: 100-continue'時,你需要監聽
continue
事件的同時設置超時。參見RFC2616 8.2.3章節以獲得更多的信息。
http.get(options, callback)
Since most requests are GET requests without bodies, Node provides thisconvenience method. The only difference between this method andhttp.request()
isthat it sets the method to GET and calls req.end()
automatically.
由於大部分請求是不包含正文的GET請求,Node提供了這個方便的方法。與http.request()
唯一的區別是此方法將請求方式設置爲GET,並且自動調用req.end()
。
Example:
例子:
<code><span class="sh_keyword">var</span> options <span class="sh_symbol">=</span> <span class="sh_cbracket">{</span> host<span class="sh_symbol">:</span> <span class="sh_string">'www.google.com'</span><span class="sh_symbol">,</span> port<span class="sh_symbol">:</span> <span class="sh_number">80</span><span class="sh_symbol">,</span> path<span class="sh_symbol">:</span> <span class="sh_string">'/index.html'</span> <span class="sh_cbracket">}</span><span class="sh_symbol">;</span> http<span class="sh_symbol">.</span><span class="sh_function">get</span><span class="sh_symbol">(</span>options<span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>res<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"Got response: "</span> <span class="sh_symbol">+</span> res<span class="sh_symbol">.</span>statusCode<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">).</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'error'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>e<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"Got error: "</span> <span class="sh_symbol">+</span> e<span class="sh_symbol">.</span>message<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
http.Agent
http.getAgent(host, port)
http.request()
uses a special Agent
for managing multiple connections toan HTTP server. NormallyAgent
instances should not be exposed to usercode, however in certain situations it's useful to check the status of theagent.
Thehttp.getAgent()
function allows you to access the agents.
http.request()
使用一個特別的Agent
代理來管理到一個服務器的多個連接,通常Agent
對象不應該暴露給用戶。但在某些特定的情況下,檢測代理的狀態是非常有用的。http.getAgent()
函數允許你訪問代理對象。
Event: 'upgrade' 事件:'upgrade'
function (request, socket, head)
Emitted each time a server responds to a request with an upgrade. If this eventisn't being listened for, clients receiving an upgrade header will have theirconnections closed.
當服務器響應upgrade請求時觸發此事件。如果這個事件沒有被監聽,客戶端接收到upgrade頭會導致連接被關閉。
See the description of the upgrade
event for http.Server
for further details.
可以查看http.Server關於upgrade事件的解釋來了解更多內容。
Event: 'continue' 事件:'continue'
function ()
Emitted when the server sends a '100 Continue' HTTP response, usually becausethe request contained 'Expect: 100-continue'. This is an instruction thatthe client should send the request body.
當服務器發送'100 Continue'答覆時觸發此事件,這通常是因爲請求頭信息中包含'Expect: 100-continue'。此事件指示客戶端可是開始發送請求正文了。
agent.maxSockets
By default set to 5. Determines how many concurrent sockets the agent can have open.
默認值爲5,指定代理能同時併發打開的套接字數量。
agent.sockets
An array of sockets currently in use by the Agent. Do not modify.
當前代理使用的套接字數組,不能更改。
agent.queue
A queue of requests waiting to be sent to sockets.
待發送到套接字的請求隊列。
http.ClientRequest
This object is created internally and returned from http.request()
. Itrepresents anin-progress request whose header has already been queued. The header is still mutable using thesetHeader(name, value)
,getHeader(name)
,removeHeader(name)
API.
The actual header will be sent along with the firstdata chunk or when closing the connection.
這個對象是在調用http.request()
時產生並返回的。它表示一個正在進行中且頭部信息已經排列好了的請求。這時候通過setHeader(name, value)
,getHeader(name)
,removeHeader(name)
這些API還可以改變頭部信息,實際的頭部信息將隨着第一塊數據發送,或者在關閉連接時發送出去。
To get the response, add a listener for 'response'
to the request object.'response'
will be emitted from the request object when the responseheaders have been received. The'response'
event is executed with oneargument
which is an instance ofhttp.ClientResponse
.
爲了獲得響應,爲請求對象增加一個對響應的監聽器。
During the 'response'
event, one can add listeners to theresponse object; particularly to listen for the'data'
event. Note thatthe '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 thebody. As long as a listener for'data'
is added during the'response'
event, the entire body will be caught.
在'response'
事件中,可以給響應對象添加監聽器,特別是監聽'data'
事件,注意'response'
事件在正文接收之前就已經被調用,所以不需要擔心捕獲不到正文的第一部分,一旦在'response'
事件中添加了對'data'
的監聽器,那麼整個正文將被捕獲。
<code><span class="sh_comment">// Good</span> request<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'response'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>response<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> response<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>chunk<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'BODY: '</span> <span class="sh_symbol">+</span> chunk<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_comment">// Bad - misses all or part of the body</span> request<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'response'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>response<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_function">setTimeout</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> response<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>chunk<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'BODY: '</span> <span class="sh_symbol">+</span> chunk<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_number">10</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
This is a Writable Stream
.
這是一個Writable Stream
可寫流。
This is an EventEmitter
with the following events:
這是一個包含下述事件的EventEmitter
事件觸發器:
Event 'response' 事件:'response'
function (response) { }
Emitted when a response is received to this request. This event is emitted only once. Theresponse
argument will be an instance ofhttp.ClientResponse
.
當請求的響應到達時觸發,該事件僅觸發一次。response
參數是http.ClientResponse
的一個實例。
request.write(chunk, encoding='utf8')
Sends a chunk of the body. By calling this methodmany times, the user can stream a request body to aserver--in that case it is suggested to use the['Transfer-Encoding', 'chunked']
header line whencreating the request.
發送正文中的一塊。用戶可以通過多次調用這個方法將請求正文以流的方式發送到服務器。此種情況建議在建立請求時使用['Transfer-Encoding', 'chunked']
請求頭。
The chunk
argument should be an array of integersor a string.
參數chunk
應當是一個整數數組或字符串。
The encoding
argument is optional and onlyapplies when chunk
is a string.
參數encoding
是可選的,僅在chunk
爲字符串時可用。
request.end([data], [encoding])
Finishes sending the request. If any parts of the body areunsent, it will flush them to the stream. If the request ischunked, this will send the terminating'0\r\n\r\n'
.
完成本次請求的發送。如果正文中的任何一個部分沒有來得及發送,將把他們全部刷新到流中。如果本次請求是分塊的,這個函數將發出結束字符'0\r\n\r\n'
。
If data
is specified, it is equivalent to calling request.write(data, encoding)
followed byrequest.end()
.
如果使用參數data,就等於在調用request.write(data, encoding)之後緊接着調用request.end()。
request.abort()
Aborts a request. (New since v0.3.8.)
阻止一個請求。(v0.3.8中新增的方法。)
http.ClientResponse
This object is created when making a request with http.request()
. It ispassed to the'response'
event of the request object.
這個對象在使用http.request()
發起請求時被創建,它會以參數的形式傳遞給request對象的'response'
事件。
The response implements the Readable Stream
interface.
'response'實現了可讀流的接口。
Event: 'data' 事件:'data'
function (chunk) {}
Emitted when a piece of the message body is received.
當接收到消息正文一部分的時候觸發。
Event: 'end' 事件:'end'
function () {}
Emitted exactly once for each message. No arguments. Afteremitted no other events will be emitted on the response.
對每次消息請求只觸發一次,該事件被觸發後將不會再有任何事件在響應中被觸發。
response.statusCode
The 3-digit HTTP response status code. E.G. 404
.
3個數字組成的HTTP響應狀態嗎。例如404
。
response.httpVersion
The HTTP version of the connected-to server. Probably either'1.1'
or'1.0'
.Also response.httpVersionMajor
is the first integer andresponse.httpVersionMinor
is the second.
連接至服務器端的HTTP版本,可能的值爲'1.1'
or '1.0'
,你也可以使用response.httpVersionMajor
獲得版本號第一位,使用response.httpVersionMinor
獲得版本號第二位。
response.headers
The response headers object.
響應頭部對象。
response.trailers
The response trailers object. Only populated after the 'end' event.
響應尾部對象,在'end'事件發生後填充該對象。
response.setEncoding(encoding=null)
Set the encoding for the response body. Either 'utf8'
, 'ascii'
, or'base64'
.Defaults to null
, which means that the 'data'
event will emit aBuffer
object..
設置響應正文的編碼,可以是'utf8'
,'ascii'
,或者'base64'
。默認值爲null
,此種情況下'data'
事件將發送緩衝器對象。
response.pause()
Pauses response from emitting events. Useful to throttle back a download.
暫停響應的事件激發,對控制下載流量非常有用。
response.resume()
Resumes a paused response.
恢復一個已經暫停的響應。
## HTTPS HTTPS模塊
HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as aseparate module.
HTTPS是基於TLS(Transport Layer Security 傳輸層安全)/SSL(Secure Sockets Layer 安全套接層)的HTTP協議,在Node中,它作爲一個獨立的模塊被實現
https.Server
https.createServer
Example:
例子:
<code><span class="sh_comment">// curl -k https://localhost:8000/</span> <span class="sh_keyword">var</span> https <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'https'</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> fs <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'fs'</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> options <span class="sh_symbol">=</span> <span class="sh_cbracket">{</span> key<span class="sh_symbol">:</span> fs<span class="sh_symbol">.</span><span class="sh_function">readFileSync</span><span class="sh_symbol">(</span><span class="sh_string">'test/fixtures/keys/agent2-key.pem'</span><span class="sh_symbol">),</span> cert<span class="sh_symbol">:</span> fs<span class="sh_symbol">.</span><span class="sh_function">readFileSync</span><span class="sh_symbol">(</span><span class="sh_string">'test/fixtures/keys/agent2-cert.pem'</span><span class="sh_symbol">)</span> <span class="sh_cbracket">}</span><span class="sh_symbol">;</span> https<span class="sh_symbol">.</span><span class="sh_function">createServer</span><span class="sh_symbol">(</span>options<span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>req<span class="sh_symbol">,</span> res<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> res<span class="sh_symbol">.</span><span class="sh_function">writeHead</span><span class="sh_symbol">(</span><span class="sh_number">200</span><span class="sh_symbol">);</span> res<span class="sh_symbol">.</span><span class="sh_function">end</span><span class="sh_symbol">(</span><span class="sh_string">"hello world</span><span class="sh_specialchar">\n</span><span class="sh_string">"</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">).</span><span class="sh_function">listen</span><span class="sh_symbol">(</span><span class="sh_number">8000</span><span class="sh_symbol">);</span></code>
https.request(options, callback)
Makes a request to a secure web server.Similar options to http.request()
.
向安全的web服務器發送請求,可選參數和http.request()
類似。
Example:
例子:
<code><span class="sh_keyword">var</span> https <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'https'</span><span class="sh_symbol">);</span> <span class="sh_keyword">var</span> options <span class="sh_symbol">=</span> <span class="sh_cbracket">{</span> host<span class="sh_symbol">:</span> <span class="sh_string">'encrypted.google.com'</span><span class="sh_symbol">,</span> port<span class="sh_symbol">:</span> <span class="sh_number">443</span><span class="sh_symbol">,</span> path<span class="sh_symbol">:</span> <span class="sh_string">'/'</span><span class="sh_symbol">,</span> method<span class="sh_symbol">:</span> <span class="sh_string">'GET'</span> <span class="sh_cbracket">}</span><span class="sh_symbol">;</span> <span class="sh_keyword">var</span> req <span class="sh_symbol">=</span> https<span class="sh_symbol">.</span><span class="sh_function">request</span><span class="sh_symbol">(</span>options<span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>res<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"statusCode: "</span><span class="sh_symbol">,</span> res<span class="sh_symbol">.</span>statusCode<span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"headers: "</span><span class="sh_symbol">,</span> res<span class="sh_symbol">.</span>headers<span class="sh_symbol">);</span> res<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>d<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> process<span class="sh_symbol">.</span>stdout<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span>d<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> req<span class="sh_symbol">.</span><span class="sh_function">end</span><span class="sh_symbol">();</span> req<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'error'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>e<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">error</span><span class="sh_symbol">(</span>e<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
The options argument has the following options
options參數可包含以下內容:
- host: IP or domain of host to make request to. Defaults to
'localhost'
.host: 要訪問的主機的IP地址或域名。默認爲'localhost'
。 - port: port of host to request to. Defaults to 443.port: 要訪問的主機端口。默認爲433。
- path: Path to request. Default
'/'
.path: 要訪問的路徑。默認爲'/'
。 - method: HTTP request method. Default
'GET'
.method: HTTP請求方式。默認爲'GET'
。 - key: Private key to use for SSL. Default
null
.key: SSL所使用的私鑰。默認爲null
。 - cert: Public x509 certificate to use. Default
null
.cert: 所使用的x509公鑰證書。默認爲null
。 - ca: An authority certificate or array of authority certificates to checkthe remote host against.ca: 用於驗證遠程主機身份的一個認證中心證書(或多個認證中心證書數組)。
https.get(options, callback)
Like http.get()
but for HTTPS.
類似http.get()
但它基於HTTPS協議。
Example:
例子:
<code><span class="sh_keyword">var</span> https <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'https'</span><span class="sh_symbol">);</span> https<span class="sh_symbol">.</span><span class="sh_function">get</span><span class="sh_symbol">(</span><span class="sh_cbracket">{</span> host<span class="sh_symbol">:</span> <span class="sh_string">'encrypted.google.com'</span><span class="sh_symbol">,</span> path<span class="sh_symbol">:</span> <span class="sh_string">'/'</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>res<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"statusCode: "</span><span class="sh_symbol">,</span> res<span class="sh_symbol">.</span>statusCode<span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"headers: "</span><span class="sh_symbol">,</span> res<span class="sh_symbol">.</span>headers<span class="sh_symbol">);</span> res<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>d<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> process<span class="sh_symbol">.</span>stdout<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span>d<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">).</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'error'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>e<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">error</span><span class="sh_symbol">(</span>e<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
URL URL模塊
This module has utilities for URL resolution and parsing.Call require('url')
to use it.
此模塊包含用於解析和分析URL的工具。可通過require('url')
訪問他們。
Parsed URL objects have some or all of the following fields, depending onwhether or not they exist in the URL string. Any parts that are not in the URLstring will not be in the parsed object. Examples are shown for the URL
解析後的URL對象包含下述部分或全部字段。具體包含哪些字段取決於解析前的URL字符串中是否存在這些字段。在原始的URL字符串中不存在的字段在解析後的對象中也不會包含。以下面這個URL爲例:
'http://user:[email protected]:8080/p/a/t/h?query=string#hash'
-
href
: The full URL that was originally parsed.href
:完整的原始URL字符串。Example:
'http://user:[email protected]:8080/p/a/t/h?query=string#hash'
例如:
'http://user:[email protected]:8080/p/a/t/h?query=string#hash'
-
protocol
: The request protocol.protocol
:請求所使用的協議。Example:
'http:'
例如:
'http:'
-
host
: The full host portion of the URL, including port and authentication information.host
:URL中關於主機的完整信息,包括端口以及用戶身份驗證信息。Example:
'user:[email protected]:8080'
例如:
'user:[email protected]:8080'
-
auth
: The authentication information portion of a URL.auth
:URL中的用戶身份驗證信息。Example:
'user:pass'
例如:
'user:pass'
-
hostname
: Just the hostname portion of the host.hostname
:主機信息中的主機名部分。Example:
'host.com'
例如:
'host.com'
-
port
: The port number portion of the host.port
:主機信息中的端口部分。Example:
'8080'
例如:
'8080'
-
pathname
: The path section of the URL, that comes after the host and before the query, including the initial slash if present.pathname
:URL中的路徑部分,這部分信息位於主機信息之後查詢字符串之前。如果存在最上層根目錄符號'/'
,也將包含在此信息中。Example:
'/p/a/t/h'
例如:
'/p/a/t/h'
-
search
: The 'query string' portion of the URL, including the leading question mark.search
:URL中的'query string'(查詢字符串)部分,包括前導的'?'
。Example:
'?query=string'
例如:
'?query=string'
-
query
: Either the 'params' portion of the query string, or a querystring-parsed object.query
:查詢字符串中的參數部分,或者是由查詢字符串解析出的對象。Example:
'query=string'
or{'query':'string'}
例如:
'query=string'
or{'query':'string'}
-
hash
: The 'fragment' portion of the URL including the pound-sign.hash
:URL中的錨點部分,包含前導的'#'
。Example:
'#hash'
例如:
'#hash'
The following methods are provided by the URL module:
URL模塊提供瞭如下方法:
url.parse(urlStr, parseQueryString=false)
Take a URL string, and return an object. Pass true
as the second argument to also parsethe query string using thequerystring
module.
以一個 URL字符串爲參數,返回一個解析後的對象。如設置第二個參數爲true
,則會使用querystring
模塊解析URL中的查詢字符串。
url.format(urlObj)
Take a parsed URL object, and return a formatted URL string.
以一個解析後的URL對象爲參數,返回格式化的URL字符串。
url.resolve(from, to)
Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.
指定一個默認URL地址,和一個鏈接的目標URL地址,返回鏈接的絕對URL地址。處理方式與瀏覽器處理錨點標籤的方法一致。## Query String 查詢字符串模塊
This module provides utilities for dealing with query strings.It provides the following methods:
該模塊爲處理查詢字符串提供了一些實用的功能。包括如下的方法:
querystring.stringify(obj, sep='&', eq='=')
Serialize an object to a query string.Optionally override the default separator and assignment characters.
將一個對象序列化爲一個查詢字符串,可選擇是否覆蓋默認的分隔符和賦值符。
Example:
例如:
<code>querystring<span class="sh_symbol">.</span><span class="sh_function">stringify</span><span class="sh_symbol">(</span><span class="sh_cbracket">{</span>foo<span class="sh_symbol">:</span> <span class="sh_string">'bar'</span><span class="sh_cbracket">}</span><span class="sh_symbol">)</span> <span class="sh_comment">// returns</span> <span class="sh_string">'foo=bar'</span> querystring<span class="sh_symbol">.</span><span class="sh_function">stringify</span><span class="sh_symbol">(</span><span class="sh_cbracket">{</span>foo<span class="sh_symbol">:</span> <span class="sh_string">'bar'</span><span class="sh_symbol">,</span> baz<span class="sh_symbol">:</span> <span class="sh_string">'bob'</span><span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_string">';'</span><span class="sh_symbol">,</span> <span class="sh_string">':'</span><span class="sh_symbol">)</span> <span class="sh_comment">// returns</span> <span class="sh_string">'foo:bar;baz:bob'</span></code>
querystring.parse(str, sep='&', eq='=')
Deserialize a query string to an object.Optionally override the default separator and assignment characters.
將一個查詢字符串反序列化爲一個對象,可選擇是否覆蓋默認的分隔符和賦值符。
Example:
例如:
<code>querystring<span class="sh_symbol">.</span><span class="sh_function">parse</span><span class="sh_symbol">(</span><span class="sh_string">'a=b&b=c'</span><span class="sh_symbol">)</span> <span class="sh_comment">// returns</span> <span class="sh_cbracket">{</span> a<span class="sh_symbol">:</span> <span class="sh_string">'b'</span><span class="sh_symbol">,</span> b<span class="sh_symbol">:</span> <span class="sh_string">'c'</span> <span class="sh_cbracket">}</span></code>
querystring.escape
The escape function used by querystring.stringify
,provided so that it could be overridden if necessary.
由querystring.stringify
使用的轉義函數,需要時可重置其內容。
querystring.unescape
The unescape function used by querystring.parse
,provided so that it could be overridden if necessary.
由querystring.parse
使用的反轉義函數,需要時可重置其內容。
REPL 交互式解釋器
A Read-Eval-Print-Loop (REPL) is available both as a standalone program and easilyincludable in other programs. REPL provides a way to interactively runJavaScript and see the results. It can be used for debugging, testing, orjust trying things out.
交互式解釋器(REPL)既可以作爲一個獨立的程序運行,也可以很容易地包含在其他程序中作爲整體程序的一部分使用。REPL爲運行JavaScript腳本與查看運行結果提供了一種交互方式,通常REPL交互方式可以用於調試、測試以及試驗某種想法。
By executing node
without any arguments from the command-line you will bedropped into the REPL. It has simplistic emacs line-editing.
在命令行中不帶任何參數地運行node
命令,就可以進入REPL環境,在該環境下你可以進行一些類似Emacs的行編輯操作。
<code>mjr<span class="sh_symbol">:~</span>$ node Type <span class="sh_string">'.help'</span> <span class="sh_keyword">for</span> options<span class="sh_symbol">.</span> <span class="sh_symbol">></span> a <span class="sh_symbol">=</span> <span class="sh_symbol">[</span> <span class="sh_number">1</span><span class="sh_symbol">,</span> <span class="sh_number">2</span><span class="sh_symbol">,</span> <span class="sh_number">3</span><span class="sh_symbol">];</span> <span class="sh_symbol">[</span> <span class="sh_number">1</span><span class="sh_symbol">,</span> <span class="sh_number">2</span><span class="sh_symbol">,</span> <span class="sh_number">3</span> <span class="sh_symbol">]</span> <span class="sh_symbol">></span> a<span class="sh_symbol">.</span><span class="sh_function">forEach</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">(</span>v<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_symbol">...</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>v<span class="sh_symbol">);</span> <span class="sh_symbol">...</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_number">1</span> <span class="sh_number">2</span> <span class="sh_number">3</span></code>
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 withrlwrap
.
爲了進行高級的行編輯操作,可以設置環境變量NODE_NO_READLINE=1
並啓動node。這種情況REPL會進入標準終端設置模式,這此模式下你可以使用rlwrap
。
For example, you could add this to your bashrc file:
比如,你可以把下列設置添加到你的bashrc文件中:
<code>alias node<span class="sh_symbol">=</span><span class="sh_string">"env NODE_NO_READLINE=1 rlwrap node"</span></code>
repl.start(prompt='> ', stream=process.stdin)
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 toprocess.stdin
.
啓動一個REPL,使用prompt
作爲輸入提示符,在stream
上進行所有I/O操作。prompt
是可選參數,默認值爲>
,stream
也是可選參數,默認值爲process.stdin
。
Multiple REPLs may be started against the same running instance of node. Eachwill share the same global object but will have unique I/O.
一個node實例中可以啓動多個REPL,它們共享相同的全局對象,但擁有各自獨立的I/O。
Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:
下面是的例子展示分別在標準輸入,Unix套接字及TCP套接字上啓動的REPL示例:
<code><span class="sh_keyword">var</span> net <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">"net"</span><span class="sh_symbol">),</span> repl <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">"repl"</span><span class="sh_symbol">);</span> connections <span class="sh_symbol">=</span> <span class="sh_number">0</span><span class="sh_symbol">;</span> repl<span class="sh_symbol">.</span><span class="sh_function">start</span><span class="sh_symbol">(</span><span class="sh_string">"node via stdin> "</span><span class="sh_symbol">);</span> net<span class="sh_symbol">.</span><span class="sh_function">createServer</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">(</span>socket<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> connections <span class="sh_symbol">+=</span> <span class="sh_number">1</span><span class="sh_symbol">;</span> repl<span class="sh_symbol">.</span><span class="sh_function">start</span><span class="sh_symbol">(</span><span class="sh_string">"node via Unix socket> "</span><span class="sh_symbol">,</span> socket<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">).</span><span class="sh_function">listen</span><span class="sh_symbol">(</span><span class="sh_string">"/tmp/node-repl-sock"</span><span class="sh_symbol">);</span> net<span class="sh_symbol">.</span><span class="sh_function">createServer</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">(</span>socket<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> connections <span class="sh_symbol">+=</span> <span class="sh_number">1</span><span class="sh_symbol">;</span> repl<span class="sh_symbol">.</span><span class="sh_function">start</span><span class="sh_symbol">(</span><span class="sh_string">"node via TCP socket> "</span><span class="sh_symbol">,</span> socket<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">).</span><span class="sh_function">listen</span><span class="sh_symbol">(</span><span class="sh_number">5001</span><span class="sh_symbol">);</span></code>
Running this program from the command line will start a REPL on stdin. OtherREPL clients may connect through the Unix socket or TCP socket.telnet
is usefulfor connecting to TCP sockets, and socat
can be used to connect to both Unix
andTCP sockets.
在命令行中運行這段程序將首先使用標準輸入啓動REPL。其他的REPL終端可以通過Unix套接字或者TCP套接字進行連接。可使用telnet
程序連接到TCP套接字,而socat
程序既可以連接到Unix套接字也可以連接連接到TCP套接字。
By starting a REPL from a Unix socket-based server instead of stdin, you canconnect to a long-running node process without restarting it.
若要連接到一個長時間運行的node進程而無需重啓進程,你應該將REPL啓動在Unix套接字上,非不要將其啓動在標準輸出上。
REPL Features REPL特性
Inside the REPL, Control+D will exit. Multi-line expressions can be input.
在REPL中,操作組合鍵Control+D可以退出。可以輸入多行表達式。
The special variable _
(underscore) contains the result of the last expression.
特殊變量_
(下劃線)包含了上一表達式的結果。
<code><span class="sh_symbol">></span> <span class="sh_symbol">[</span> <span class="sh_string">"a"</span><span class="sh_symbol">,</span> <span class="sh_string">"b"</span><span class="sh_symbol">,</span> <span class="sh_string">"c"</span> <span class="sh_symbol">]</span> <span class="sh_symbol">[</span> <span class="sh_string">'a'</span><span class="sh_symbol">,</span> <span class="sh_string">'b'</span><span class="sh_symbol">,</span> <span class="sh_string">'c'</span> <span class="sh_symbol">]</span> <span class="sh_symbol">></span> _<span class="sh_symbol">.</span>length <span class="sh_number">3</span> <span class="sh_symbol">></span> _ <span class="sh_symbol">+=</span> <span class="sh_number">1</span> <span class="sh_number">4</span></code>
The REPL provides access to any variables in the global scope. You can expose a variableto the REPL explicitly by assigning it to thecontext
object associated with eachREPLServer
. For example:
在REPL可以訪問全局作用域中的任何變量。爲了在REPL中訪問一個變量,你只要將此變量顯性地分配給相應REPLServer
的context
對象。示例如下:
<code><span class="sh_comment">// repl_test.js</span> <span class="sh_keyword">var</span> repl <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">"repl"</span><span class="sh_symbol">),</span> msg <span class="sh_symbol">=</span> <span class="sh_string">"message"</span><span class="sh_symbol">;</span> repl<span class="sh_symbol">.</span><span class="sh_function">start</span><span class="sh_symbol">().</span>context<span class="sh_symbol">.</span>m <span class="sh_symbol">=</span> msg<span class="sh_symbol">;</span></code>
Things in the context
object appear as local within the REPL:
context
對象中的變量在REPL中看起來就像是本地變量。
<code>mjr<span class="sh_symbol">:~</span>$ node repl_test<span class="sh_symbol">.</span>js <span class="sh_symbol">></span> m <span class="sh_string">'message'</span></code>
There are a few special REPL commands:
以下是另外一些特殊的REPL命令:
.break
- While inputting a multi-line expression, sometimes you get lostor just don't care about completing it..break
will start over..break
- 當你輸入多行表達式,如果想放棄當前的輸入,可以用.break
跳出。.clear
- Resets thecontext
object to an empty object and clears any multi-line expression..clear
- 將context
重置爲空對象,並清空當前正在輸入的多行表達式。.exit
- Close the I/O stream, which will cause the REPL to exit..exit
- 該命令用於關閉I/O流,並退出REPL。.help
- Show this list of special commands..help
- 輸出特殊命令的列表。
Child Processes 子進程
Node provides a tri-directional popen(3)
facility through the ChildProcess
class.
在Node裏,ChildProcess
類提供了一個3向的popen(3)
機制。
It is possible to stream data through the child's stdin
, stdout
, andstderr
in a fully non-blocking way.
子進程類中的stdin
, stdout
,和stderr
可以使數據流以完全非阻塞式的方式(non-blocking way)流動(stream)
To create a child process use require('child_process').spawn()
.
調用require('child_process').spawn()
可以創建一個子進程(child process)
Child processes always have three streams associated with them. child.stdin
,child.stdout
, andchild.stderr
.
child.stdin
,child.stdout
,和 child.stderr
等3個流總是伴隨着子進程。
ChildProcess
is an EventEmitter
.
ChildProcess
是一種 EventEmitter
(事件觸發器)。
Event: 'exit' 事件:'exit'
function (code, signal) {}
This event is emitted after the child process ends. If the process terminatednormally,code
is the final exit code of the process, otherwise null
. Ifthe process terminated due to receipt of a signal,signal
is the string
nameof the signal, otherwise null
.
當子進程結束時,(Node)觸發該事件。如果進程正常終結,那麼進程的最終退出代碼( final exit code)爲code
,否則爲null
。如果進程的結束是因爲接收到一個信號,那麼signal
爲string型的信號名稱,否則爲null
。
See waitpid(2)
.
參見waitpid(2)
。
child.stdin
A Writable Stream
that represents the child process's stdin
.Closing this stream viaend()
often causes the child process to terminate.
一個Writable Stream
(可寫流),表示子進程的stdin
。調用end()
來關閉這個流通常會終結整個子進程。
child.stdout
A Readable Stream
that represents the child process's stdout
.
一個Readable Stream
(可讀流),表示子進程的stdout
(標準輸出)。
child.stderr
A Readable Stream
that represents the child process's stderr
.
一個Readable Stream
(可讀流),表示子進程的stderr
(標準錯誤)。
child.pid
The PID of the child process.
子進程的PID(進程編號)。
Example:
例如:
<code><span class="sh_keyword">var</span> spawn <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'child_process'</span><span class="sh_symbol">).</span>spawn<span class="sh_symbol">,</span> grep <span class="sh_symbol">=</span> <span class="sh_function">spawn</span><span class="sh_symbol">(</span><span class="sh_string">'grep'</span><span class="sh_symbol">,</span> <span class="sh_symbol">[</span><span class="sh_string">'ssh'</span><span class="sh_symbol">]);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Spawned child pid: '</span> <span class="sh_symbol">+</span> grep<span class="sh_symbol">.</span>pid<span class="sh_symbol">);</span> grep<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">end</span><span class="sh_symbol">();</span></code>
child_process.spawn(command, args=[], [options])
Launches a new process with the given command
, with command line arguments inargs
.If omitted, args
defaults to an empty Array.
使用指定的command
創建一個新進程,命令行參數爲args
。缺省下,args
默認爲一個空數組。
The third argument is used to specify additional options, which defaults to:
第三個參數用於指定附加的選項,默認如下:
<code><span class="sh_cbracket">{</span> cwd<span class="sh_symbol">:</span> <span class="sh_predef_var">undefined</span><span class="sh_symbol">,</span> env<span class="sh_symbol">:</span> process<span class="sh_symbol">.</span>env<span class="sh_symbol">,</span> customFds<span class="sh_symbol">:</span> <span class="sh_symbol">[-</span><span class="sh_number">1</span><span class="sh_symbol">,</span> <span class="sh_symbol">-</span><span class="sh_number">1</span><span class="sh_symbol">,</span> <span class="sh_symbol">-</span><span class="sh_number">1</span><span class="sh_symbol">],</span> setsid<span class="sh_symbol">:</span> <span class="sh_keyword">false</span> <span class="sh_cbracket">}</span></code>
cwd
allows you to specify the working directory from which the process is spawned.Useenv
to specify environment variables that will be visible to the new process.WithcustomFds
it is possible to hook up the new process'
[stdin, stout, stderr] toexisting 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.
參數cwd
允許你指定要創建的子進程的工作目錄(working directory)。參數env
可以指定哪些環境變量在新進程中是可見的。參數customFds
可以使新進程中的[stdin, stout, stderr]和已存在的流進行掛接(hook up)。參數-1
可以建立一個新的流。如果設置參數setsid
爲true,該子進程將轉入到一個新會話(session)中運行。
Example of running ls -lh /usr
, capturing stdout
, stderr
, and the exit code:
例:運行ls -lh /usr
命令,捕獲stdout
,stderr
和退出代碼:
<code><span class="sh_keyword">var</span> util <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'util'</span><span class="sh_symbol">),</span> spawn <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'child_process'</span><span class="sh_symbol">).</span>spawn<span class="sh_symbol">,</span> ls <span class="sh_symbol">=</span> <span class="sh_function">spawn</span><span class="sh_symbol">(</span><span class="sh_string">'ls'</span><span class="sh_symbol">,</span> <span class="sh_symbol">[</span><span class="sh_string">'-lh'</span><span class="sh_symbol">,</span> <span class="sh_string">'/usr'</span><span class="sh_symbol">]);</span> ls<span class="sh_symbol">.</span>stdout<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>data<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'stdout: '</span> <span class="sh_symbol">+</span> data<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> ls<span class="sh_symbol">.</span>stderr<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>data<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'stderr: '</span> <span class="sh_symbol">+</span> data<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> ls<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'exit'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>code<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'child process exited with code '</span> <span class="sh_symbol">+</span> code<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
Example: A very elaborate way to run 'ps ax | grep ssh'
例:運行'ps ax | grep ssh'命令的完整方法:
<code><span class="sh_keyword">var</span> util <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'util'</span><span class="sh_symbol">),</span> spawn <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'child_process'</span><span class="sh_symbol">).</span>spawn<span class="sh_symbol">,</span> ps <span class="sh_symbol">=</span> <span class="sh_function">spawn</span><span class="sh_symbol">(</span><span class="sh_string">'ps'</span><span class="sh_symbol">,</span> <span class="sh_symbol">[</span><span class="sh_string">'ax'</span><span class="sh_symbol">]),</span> grep <span class="sh_symbol">=</span> <span class="sh_function">spawn</span><span class="sh_symbol">(</span><span class="sh_string">'grep'</span><span class="sh_symbol">,</span> <span class="sh_symbol">[</span><span class="sh_string">'ssh'</span><span class="sh_symbol">]);</span> ps<span class="sh_symbol">.</span>stdout<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>data<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> grep<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">write</span><span class="sh_symbol">(</span>data<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> ps<span class="sh_symbol">.</span>stderr<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>data<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'ps stderr: '</span> <span class="sh_symbol">+</span> data<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> ps<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'exit'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>code<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>code <span class="sh_symbol">!==</span> <span class="sh_number">0</span><span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'ps process exited with code '</span> <span class="sh_symbol">+</span> code<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span> grep<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">end</span><span class="sh_symbol">();</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> grep<span class="sh_symbol">.</span>stdout<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>data<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span>data<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> grep<span class="sh_symbol">.</span>stderr<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>data<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'grep stderr: '</span> <span class="sh_symbol">+</span> data<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> grep<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'exit'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>code<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>code <span class="sh_symbol">!==</span> <span class="sh_number">0</span><span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'grep process exited with code '</span> <span class="sh_symbol">+</span> code<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
Example of checking for failed exec:
檢測exec執行是否失敗的例子:
<code><span class="sh_keyword">var</span> spawn <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'child_process'</span><span class="sh_symbol">).</span>spawn<span class="sh_symbol">,</span> child <span class="sh_symbol">=</span> <span class="sh_function">spawn</span><span class="sh_symbol">(</span><span class="sh_string">'bad_command'</span><span class="sh_symbol">);</span> child<span class="sh_symbol">.</span>stderr<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'data'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>data<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span><span class="sh_regexp">/^execvp\(\)/</span><span class="sh_symbol">.</span><span class="sh_function">test</span><span class="sh_symbol">(</span>data<span class="sh_symbol">.</span><span class="sh_function">asciiSlice</span><span class="sh_symbol">(</span><span class="sh_number">0</span><span class="sh_symbol">,</span>data<span class="sh_symbol">.</span>length<span class="sh_symbol">)))</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'Failed to start child process.'</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
See also: child_process.exec()
可參見:child_process.exec()
child_process.exec(command, [options], callback)
High-level way to execute a command as a child process, buffer theoutput, and return it all in a callback.
以子進程方式執行一個命令的高級方法。所有輸出經過緩衝後在同一個回調函數中返回。
<code><span class="sh_keyword">var</span> util <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'util'</span><span class="sh_symbol">),</span> exec <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'child_process'</span><span class="sh_symbol">).</span>exec<span class="sh_symbol">,</span> child<span class="sh_symbol">;</span> child <span class="sh_symbol">=</span> <span class="sh_function">exec</span><span class="sh_symbol">(</span><span class="sh_string">'cat *.js bad_file | wc -l'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>error<span class="sh_symbol">,</span> stdout<span class="sh_symbol">,</span> stderr<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'stdout: '</span> <span class="sh_symbol">+</span> stdout<span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'stderr: '</span> <span class="sh_symbol">+</span> stderr<span class="sh_symbol">);</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>error <span class="sh_symbol">!==</span> <span class="sh_keyword">null</span><span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'exec error: '</span> <span class="sh_symbol">+</span> error<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
The callback gets the arguments (error, stdout, stderr)
. On success,error
will be null
. On error, error
will be an instance ofError
and err.code
will be the exit code of the child process,
anderr.signal
will be set to thesignal that terminated the process.
回調函數獲得(error, stdout, stderr)
3個參數。成功時,error
爲null
。錯誤時error
爲一個Error
實例,err.code
爲該子進程的退出代碼,err.signal
爲使該進程結束的信號。
There is a second optional argument to specify several options. The default options are
可選的第二個參數用於指定一些選項。默認選項如下:
<code><span class="sh_cbracket">{</span> encoding<span class="sh_symbol">:</span> <span class="sh_string">'utf8'</span><span class="sh_symbol">,</span> timeout<span class="sh_symbol">:</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> maxBuffer<span class="sh_symbol">:</span> <span class="sh_number">200</span><span class="sh_symbol">*</span><span class="sh_number">1024</span><span class="sh_symbol">,</span> killSignal<span class="sh_symbol">:</span> <span class="sh_string">'SIGTERM'</span><span class="sh_symbol">,</span> cwd<span class="sh_symbol">:</span> <span class="sh_keyword">null</span><span class="sh_symbol">,</span> env<span class="sh_symbol">:</span> <span class="sh_keyword">null</span> <span class="sh_cbracket">}</span></code>
If timeout
is greater than 0, then it will kill the child processif it runs longer thantimeout
milliseconds. The child process is killed withkillSignal
(default:'SIGTERM'
). maxBuffer
specifies
the largestamount of data allowed on stdout or stderr - if this value is exceeded thenthe child process is killed.
如果參數timeout
的值超過0,那麼當運行超過timeout
毫秒後子進程將終止。killSignal
爲終止子進程的信號(默認爲:'SIGTERM'
)。 參數maxBuffer
指定了stdout或stderr流最大數據量,一旦超過該值,子進程將會終止。
child.kill(signal='SIGTERM')
Send a signal to the child process. If no argument is given, the process willbe sent'SIGTERM'
. See signal(7)
for a list of available signals.
給子進程發送信號。如果沒有指定參數,(Node)將會發送'SIGTERM'
信號。在signal(7)
中可查閱到可用的信號列表。
<code><span class="sh_keyword">var</span> spawn <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'child_process'</span><span class="sh_symbol">).</span>spawn<span class="sh_symbol">,</span> grep <span class="sh_symbol">=</span> <span class="sh_function">spawn</span><span class="sh_symbol">(</span><span class="sh_string">'grep'</span><span class="sh_symbol">,</span> <span class="sh_symbol">[</span><span class="sh_string">'ssh'</span><span class="sh_symbol">]);</span> grep<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'exit'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span> <span class="sh_symbol">(</span>code<span class="sh_symbol">,</span> signal<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'child process terminated due to receipt of signal '</span><span class="sh_symbol">+</span>signal<span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span> <span class="sh_comment">// send SIGHUP to process</span> grep<span class="sh_symbol">.</span><span class="sh_function">kill</span><span class="sh_symbol">(</span><span class="sh_string">'SIGHUP'</span><span class="sh_symbol">);</span></code>
Note that while the function is called kill
, the signal delivered to the childprocess may not actually kill it.kill
really just sends a signal to a process.
注意:雖然函數名爲kill
(殺死),發送的信號並不會真正殺死子進程。kill
僅僅是向該進程發送一個信號。
See kill(2)
參見kill(2)
Assert 斷言模塊
This module is used for writing unit tests for your applications, you canaccess it withrequire('assert')
.
斷言(Assert)模塊用於爲應用編寫單元測試,可以通過require('assert')
對該模塊進行調用。
assert.fail(actual, expected, message, operator)
Tests if actual
is equal to expected
using the operator provided.
使用指定操作符測試actual
(真實值)是否和expected
(期望值)一致。
assert.ok(value, [message])
Tests if value is a true
value, it is equivalent to assert.equal(true, value, message);
測試實際值是否爲true
,和assert.equal(true, value, message);
作用一致
assert.equal(actual, expected, [message])
Tests shallow, coercive equality with the equal comparison operator ( ==
).
使用等值比較操作符( ==
)測試真實值是否淺層地(shallow),強制性地(coercive)和預期值相等。
assert.notEqual(actual, expected, [message])
Tests shallow, coercive non-equality with the not equal comparison operator ( !=
).
使用不等比較操作符( !=
)測試真實值是否淺層地(shallow),強制性地(coercive)和預期值不相等。
assert.deepEqual(actual, expected, [message])
Tests for deep equality.
測試真實值是否深層次地和預期值相等。
assert.notDeepEqual(actual, expected, [message])
Tests for any deep inequality.
測試真實值是否深層次地和預期值不相等。
assert.strictEqual(actual, expected, [message])
Tests strict equality, as determined by the strict equality operator ( ===
)
使用嚴格相等操作符 ( ===
)測試真實值是否嚴格地(strict)和預期值相等。
assert.notStrictEqual(actual, expected, [message])
Tests strict non-equality, as determined by the strict not equal operator ( !==
)
使用嚴格不相等操作符 ( !==
)測試真實值是否嚴格地(strict)和預期值不相等。
assert.throws(block, [error], [message])
Expects block
to throw an error. error
can be constructor, regexp or validation function.
預期block
時拋出一個錯誤(error), error
可以爲構造函數,正則表達式或者其他驗證器。
Validate instanceof using constructor:
使用構造函數驗證實例:
<code>assert<span class="sh_symbol">.</span><span class="sh_keyword">throws</span><span class="sh_symbol">(</span> <span class="sh_keyword">function</span><span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">throw</span> <span class="sh_keyword">new</span> <span class="sh_predef_func">Error</span><span class="sh_symbol">(</span><span class="sh_string">"Wrong value"</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_predef_func">Error</span> <span class="sh_symbol">);</span></code>
Validate error message using RegExp:
使用正則表達式驗證錯誤信息:
<code>assert<span class="sh_symbol">.</span><span class="sh_keyword">throws</span><span class="sh_symbol">(</span> <span class="sh_keyword">function</span><span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">throw</span> <span class="sh_keyword">new</span> <span class="sh_predef_func">Error</span><span class="sh_symbol">(</span><span class="sh_string">"Wrong value"</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_regexp">/value/</span> <span class="sh_symbol">);</span></code>
Custom error validation:
用戶自定義的錯誤驗證器:
<code>assert<span class="sh_symbol">.</span><span class="sh_keyword">throws</span><span class="sh_symbol">(</span> <span class="sh_keyword">function</span><span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">throw</span> <span class="sh_keyword">new</span> <span class="sh_predef_func">Error</span><span class="sh_symbol">(</span><span class="sh_string">"Wrong value"</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span> <span class="sh_symbol">(</span>err <span class="sh_keyword">instanceof</span> <span class="sh_predef_func">Error</span><span class="sh_symbol">)</span> <span class="sh_symbol">&&</span> <span class="sh_regexp">/value/</span><span class="sh_symbol">.</span><span class="sh_function">test</span><span class="sh_symbol">(</span>err<span class="sh_symbol">)</span> <span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">return</span> <span class="sh_keyword">true</span><span class="sh_symbol">;</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_string">"unexpected error"</span> <span class="sh_symbol">);</span></code>
assert.doesNotThrow(block, [error], [message])
Expects block
not to throw an error, see assert.throws for details.
預期block
時不拋出錯誤,詳細信息請見assert.throws。
assert.ifError(value)
Tests if value is not a false value, throws if it is a true value. Useful whentesting the first argument,error
in callbacks.
測試值是否不爲false,當爲true時拋出。常用於回調中第一個參數error
的測試。## TTY 終端模塊
Use require('tty')
to access this module.
可使用require('tty')
訪問此模塊。
Example:
示例:
<code><span class="sh_keyword">var</span> tty <span class="sh_symbol">=</span> <span class="sh_function">require</span><span class="sh_symbol">(</span><span class="sh_string">'tty'</span><span class="sh_symbol">);</span> tty<span class="sh_symbol">.</span><span class="sh_function">setRawMode</span><span class="sh_symbol">(</span><span class="sh_keyword">true</span><span class="sh_symbol">);</span> process<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">resume</span><span class="sh_symbol">();</span> process<span class="sh_symbol">.</span>stdin<span class="sh_symbol">.</span><span class="sh_function">on</span><span class="sh_symbol">(</span><span class="sh_string">'keypress'</span><span class="sh_symbol">,</span> <span class="sh_keyword">function</span><span class="sh_symbol">(</span>char<span class="sh_symbol">,</span> key<span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">if</span> <span class="sh_symbol">(</span>key <span class="sh_symbol">&&</span> key<span class="sh_symbol">.</span>ctrl <span class="sh_symbol">&&</span> key<span class="sh_symbol">.</span>name <span class="sh_symbol">==</span> <span class="sh_string">'c'</span><span class="sh_symbol">)</span> <span class="sh_cbracket">{</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">'graceful exit'</span><span class="sh_symbol">);</span> process<span class="sh_symbol">.</span><span class="sh_function">exit</span><span class="sh_symbol">()</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">);</span></code>
tty.open(path, args=[])
Spawns a new process with the executable pointed to by path
as the sessionleader to a new pseudo terminal.
用path
路徑所指向的可執行文件啓動一個新的進程,並將其作爲一個新的僞終端的控制進程。
Returns an array [slaveFD, childProcess]
. slaveFD
is the file descriptorof the slave end of the pseudo terminal.childProcess
is a child processobject.
返回一個數組 [slaveFD, childProcess]
。slaveFD
是這個僞終端的從設備文件描述符,childProcess
是子進程的對象。
tty.isatty(fd)
Returns true
or false
depending on if the fd
is associated with aterminal.
當fd
所表示的文件描述符與一個終端相關聯時返回true
,否則返回false
。
tty.setRawMode(mode)
mode
should be true
or false
. This sets the properties of the currentprocess's stdin fd to act either as a raw device or default.
mode
參數可以設爲true
或false
。此方法設置當前進程的stdin(標準輸入)爲原始設備方式,或默認方式。
tty.setWindowSize(fd, row, col)
ioctl
s the window size settings to the file descriptor.
使用ioctl
設置文件描述符對應的終端窗口大小(行數與列數)。
tty.getWindowSize(fd)
Returns [row, col]
for the TTY associated with the file descriptor.
返回文件描述符所對應的終端的窗口大小[row, col]
(行數與列數)。
os Module 操作系統模塊
Use require('os')
to access this module.
可以通過require('os')
訪問這個os 模塊。
os.hostname()
Returns the hostname of the operating system.
該方法返回當前操作系統的主機名。
os.type()
Returns the operating system name.
該方法返回當前操作系統名稱。
os.release()
Returns the operating system release.
返回當前操作系統的髮型版本。
os.uptime()
Returns the system uptime in seconds.
該方法返回當前系統的正常運行時間,時間以秒爲單位。
os.loadavg()
Returns an array containing the 1, 5, and 15 minute load averages.
該方法返回一個數組,該數組存儲着系統1分鐘,5分鐘,以及15分鐘的負載均值。
os.totalmem()
Returns the total amount of system memory in bytes.
返回系統存儲空間總值,該值以字節(byte)爲單位。
os.freemem()
Returns the amount of free system memory in bytes.
返回系統存儲的剩餘空間,該值以字節(byte)爲單位。
os.cpus()
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).
該方法返回一個對象數組,該數組包含了關於系統每個CPU/內核的信息:型號,速度(以MHz爲單位),以及CPU時間使用情況(包含CPU時間片在用戶態、改變過優先級的用戶進程、內核態、空閒、以及IRQ各方面的消耗)。
Example inspection of os.cpus:
os.cpus以一個示例如下:
<code><span class="sh_symbol">[</span> <span class="sh_cbracket">{</span> model<span class="sh_symbol">:</span> <span class="sh_string">'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz'</span><span class="sh_symbol">,</span> speed<span class="sh_symbol">:</span> <span class="sh_number">2926</span><span class="sh_symbol">,</span> times<span class="sh_symbol">:</span> <span class="sh_cbracket">{</span> user<span class="sh_symbol">:</span> <span class="sh_number">252020</span><span class="sh_symbol">,</span> nice<span class="sh_symbol">:</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> sys<span class="sh_symbol">:</span> <span class="sh_number">30340</span><span class="sh_symbol">,</span> idle<span class="sh_symbol">:</span> <span class="sh_number">1070356870</span><span class="sh_symbol">,</span> irq<span class="sh_symbol">:</span> <span class="sh_number">0</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_cbracket">{</span> model<span class="sh_symbol">:</span> <span class="sh_string">'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz'</span><span class="sh_symbol">,</span> speed<span class="sh_symbol">:</span> <span class="sh_number">2926</span><span class="sh_symbol">,</span> times<span class="sh_symbol">:</span> <span class="sh_cbracket">{</span> user<span class="sh_symbol">:</span> <span class="sh_number">306960</span><span class="sh_symbol">,</span> nice<span class="sh_symbol">:</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> sys<span class="sh_symbol">:</span> <span class="sh_number">26980</span><span class="sh_symbol">,</span> idle<span class="sh_symbol">:</span> <span class="sh_number">1071569080</span><span class="sh_symbol">,</span> irq<span class="sh_symbol">:</span> <span class="sh_number">0</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_cbracket">{</span> model<span class="sh_symbol">:</span> <span class="sh_string">'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz'</span><span class="sh_symbol">,</span> speed<span class="sh_symbol">:</span> <span class="sh_number">2926</span><span class="sh_symbol">,</span> times<span class="sh_symbol">:</span> <span class="sh_cbracket">{</span> user<span class="sh_symbol">:</span> <span class="sh_number">248450</span><span class="sh_symbol">,</span> nice<span class="sh_symbol">:</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> sys<span class="sh_symbol">:</span> <span class="sh_number">21750</span><span class="sh_symbol">,</span> idle<span class="sh_symbol">:</span> <span class="sh_number">1070919370</span><span class="sh_symbol">,</span> irq<span class="sh_symbol">:</span> <span class="sh_number">0</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_cbracket">{</span> model<span class="sh_symbol">:</span> <span class="sh_string">'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz'</span><span class="sh_symbol">,</span> speed<span class="sh_symbol">:</span> <span class="sh_number">2926</span><span class="sh_symbol">,</span> times<span class="sh_symbol">:</span> <span class="sh_cbracket">{</span> user<span class="sh_symbol">:</span> <span class="sh_number">256880</span><span class="sh_symbol">,</span> nice<span class="sh_symbol">:</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> sys<span class="sh_symbol">:</span> <span class="sh_number">19430</span><span class="sh_symbol">,</span> idle<span class="sh_symbol">:</span> <span class="sh_number">1070905480</span><span class="sh_symbol">,</span> irq<span class="sh_symbol">:</span> <span class="sh_number">20</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_cbracket">{</span> model<span class="sh_symbol">:</span> <span class="sh_string">'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz'</span><span class="sh_symbol">,</span> speed<span class="sh_symbol">:</span> <span class="sh_number">2926</span><span class="sh_symbol">,</span> times<span class="sh_symbol">:</span> <span class="sh_cbracket">{</span> user<span class="sh_symbol">:</span> <span class="sh_number">511580</span><span class="sh_symbol">,</span> nice<span class="sh_symbol">:</span> <span class="sh_number">20</span><span class="sh_symbol">,</span> sys<span class="sh_symbol">:</span> <span class="sh_number">40900</span><span class="sh_symbol">,</span> idle<span class="sh_symbol">:</span> <span class="sh_number">1070842510</span><span class="sh_symbol">,</span> irq<span class="sh_symbol">:</span> <span class="sh_number">0</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_cbracket">{</span> model<span class="sh_symbol">:</span> <span class="sh_string">'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz'</span><span class="sh_symbol">,</span> speed<span class="sh_symbol">:</span> <span class="sh_number">2926</span><span class="sh_symbol">,</span> times<span class="sh_symbol">:</span> <span class="sh_cbracket">{</span> user<span class="sh_symbol">:</span> <span class="sh_number">291660</span><span class="sh_symbol">,</span> nice<span class="sh_symbol">:</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> sys<span class="sh_symbol">:</span> <span class="sh_number">34360</span><span class="sh_symbol">,</span> idle<span class="sh_symbol">:</span> <span class="sh_number">1070888000</span><span class="sh_symbol">,</span> irq<span class="sh_symbol">:</span> <span class="sh_number">10</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_cbracket">{</span> model<span class="sh_symbol">:</span> <span class="sh_string">'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz'</span><span class="sh_symbol">,</span> speed<span class="sh_symbol">:</span> <span class="sh_number">2926</span><span class="sh_symbol">,</span> times<span class="sh_symbol">:</span> <span class="sh_cbracket">{</span> user<span class="sh_symbol">:</span> <span class="sh_number">308260</span><span class="sh_symbol">,</span> nice<span class="sh_symbol">:</span> <span class="sh_number">0</span><span class="sh_symbol">,</span> sys<span class="sh_symbol">:</span> <span class="sh_number">55410</span><span class="sh_symbol">,</span> idle<span class="sh_symbol">:</span> <span class="sh_number">1071129970</span><span class="sh_symbol">,</span> irq<span class="sh_symbol">:</span> <span class="sh_number">880</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_cbracket">{</span> model<span class="sh_symbol">:</span> <span class="sh_string">'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz'</span><span class="sh_symbol">,</span> speed<span class="sh_symbol">:</span> <span class="sh_number">2926</span><span class="sh_symbol">,</span> times<span class="sh_symbol">:</span> <span class="sh_cbracket">{</span> user<span class="sh_symbol">:</span> <span class="sh_number">266450</span><span class="sh_symbol">,</span> nice<span class="sh_symbol">:</span> <span class="sh_number">1480</span><span class="sh_symbol">,</span> sys<span class="sh_symbol">:</span> <span class="sh_number">34920</span><span class="sh_symbol">,</span> idle<span class="sh_symbol">:</span> <span class="sh_number">1072572010</span><span class="sh_symbol">,</span> irq<span class="sh_symbol">:</span> <span class="sh_number">30</span> <span class="sh_cbracket">}</span> <span class="sh_cbracket">}</span> <span class="sh_symbol">]</span></code>
Debugger 調試器
V8 comes with an extensive debugger which is accessible out-of-process via asimpleTCP protocol.Node has a built-in client for
this debugger. To use this, start Node with thedebug
argument; a prompt will appear:
V8引擎自身配備了全面的調試器,該調試器通過簡單的TCP協議在進程外訪問。Node中內置了該調試器的客戶端,要使用它可以在啓動Node時附加debug
參數,此模式下將顯示debug提示符:
<code><span class="sh_symbol">%</span> node debug myscript<span class="sh_symbol">.</span>js debug<span class="sh_symbol">></span></code>
At this point myscript.js
is not yet running. To start the script, enterthe commandrun
. If everything works okay, the output should look likethis:
此時 myscript.js
還沒有開始執行,若要執行這段腳本,還需要輸入run
命令。如果一切運行正常的話輸出信息應該如下所示:
<code><span class="sh_symbol">%</span> node debug myscript<span class="sh_symbol">.</span>js debug<span class="sh_symbol">></span> run <span class="sh_keyword">debugger</span> listening on port <span class="sh_number">5858</span> connecting<span class="sh_symbol">...</span>ok</code>
Node's debugger client doesn't support the full range of commands, butsimple step and inspection is possible. By putting the statementdebugger;
into the source code of your script, you will enable a breakpoint.
Node的調試器客戶端雖然沒有支持所有的命令,但是實現簡單的單步調試還是可以的。你可以在腳本代碼中聲明debugger;
語句從而啓用一個斷點。
For example, suppose myscript.js
looked like this:
例如,假設myscript.js
代碼如下:
<code><span class="sh_comment">// myscript.js</span> x <span class="sh_symbol">=</span> <span class="sh_number">5</span><span class="sh_symbol">;</span> <span class="sh_function">setTimeout</span><span class="sh_symbol">(</span><span class="sh_keyword">function</span> <span class="sh_symbol">()</span> <span class="sh_cbracket">{</span> <span class="sh_keyword">debugger</span><span class="sh_symbol">;</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"world"</span><span class="sh_symbol">);</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_number">1000</span><span class="sh_symbol">);</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"hello"</span><span class="sh_symbol">);</span></code>
Then once the debugger is run, it will break on line 4.
一旦調試器開始運行,那麼它將在執行到第4行代碼處時停止。
<code><span class="sh_symbol">%</span> <span class="sh_symbol">./</span>node debug myscript<span class="sh_symbol">.</span>js debug<span class="sh_symbol">></span> run <span class="sh_keyword">debugger</span> listening on port <span class="sh_number">5858</span> connecting<span class="sh_symbol">...</span>ok hello <span class="sh_keyword">break</span> <span class="sh_keyword">in</span> #<span class="sh_symbol"><</span>an <span class="sh_predef_func">Object</span><span class="sh_symbol">>.</span><span class="sh_function">_onTimeout</span><span class="sh_symbol">(),</span> myscript<span class="sh_symbol">.</span>js<span class="sh_symbol">:</span><span class="sh_number">4</span> <span class="sh_keyword">debugger</span><span class="sh_symbol">;</span> <span class="sh_symbol">^</span> debug<span class="sh_symbol">></span> next <span class="sh_keyword">break</span> <span class="sh_keyword">in</span> #<span class="sh_symbol"><</span>an <span class="sh_predef_func">Object</span><span class="sh_symbol">>.</span><span class="sh_function">_onTimeout</span><span class="sh_symbol">(),</span> myscript<span class="sh_symbol">.</span>js<span class="sh_symbol">:</span><span class="sh_number">5</span> console<span class="sh_symbol">.</span><span class="sh_function">log</span><span class="sh_symbol">(</span><span class="sh_string">"world"</span><span class="sh_symbol">);</span> <span class="sh_symbol">^</span> debug<span class="sh_symbol">></span> print x <span class="sh_number">5</span> debug<span class="sh_symbol">></span> print <span class="sh_number">2+2</span> <span class="sh_number">4</span> debug<span class="sh_symbol">></span> next world <span class="sh_keyword">break</span> <span class="sh_keyword">in</span> #<span class="sh_symbol"><</span>an <span class="sh_predef_func">Object</span><span class="sh_symbol">>.</span><span class="sh_function">_onTimeout</span><span class="sh_symbol">()</span> returning <span class="sh_predef_var">undefined</span><span class="sh_symbol">,</span> myscript<span class="sh_symbol">.</span>js<span class="sh_symbol">:</span><span class="sh_number">6</span> <span class="sh_cbracket">}</span><span class="sh_symbol">,</span> <span class="sh_number">1000</span><span class="sh_symbol">);</span> <span class="sh_symbol">^</span> debug<span class="sh_symbol">></span> quit A debugging session is active<span class="sh_symbol">.</span> Quit anyway<span class="sh_symbol">?</span> <span class="sh_symbol">(</span>y or n<span class="sh_symbol">)</span> y <span class="sh_symbol">%</span></code>
The print
command allows you to evaluate variables. The next
command stepsover to the next line. There are a few other commands available and more tocome typehelp
to see others.
print
命令允許將變量輸出到控制檯進行查看。next
命令單步調試到下一行代碼。還有其他一些可用的命令你可以通過輸入help
進行查看。
Advanced Usage 高級用法
The V8 debugger can be enabled and accessed either by starting Node withthe --debug
command-line flag or by signaling an existing Node processwith SIGUSR1
.
要啓用V8引擎調試器你可以在啓動Node時增加命令行參數--debug
或者給一個已經存在的Node進程發送值爲SIGUSR1
的信號量。
Appendixes 附錄
Appendix 1 - Third Party Modules 附錄 1 - 第三方模塊
There are many third party modules for Node. At the time of writing, August2010, the master repository of modules isthe wiki page.
Node中包含許多第三方模塊。截至撰寫時(2010年8月),此wiki頁是存放Node模塊的主倉庫。
This appendix is intended as a SMALL guide to new-comers to help themquickly find what are considered to be quality modules. It is not intendedto be a complete list. There may be better more complete modules foundelsewhere.
本附錄的編寫目的在於簡要指導Node的新用戶,幫助他們可以迅速找到公認的優秀Node模塊。這裏並非一份完整的列表,在其他地方也許可以找到其他更好更完善的模塊。
-
Module Installer: npm
模塊安裝:npm
-
HTTP Middleware: Connect
HTTP中間件(Middleware):Connect
-
Web Framework: Express
Web框架:Express
-
Web Sockets: Socket.IO
-
HTML Parsing: HTML5
HTML解析器:HTML5
-
Serialization: msgpack
序列化工具:msgpack
-
Scraping: Apricot
抓取器:Apricot
-
Debugger: ndb is a CLI debuggerinspector is a web basedtool.
-
Testing/TDD/BDD: vows,expresso,mjsunit.runner
測試工具/TDD/BDD: vows,expresso,mjsunit.runner
Patches to this list are welcome.