forked from nodejscn/node-api-cn
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
130 changed files
with
956 additions
and
136 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
# node-api-cn | ||
Node.js API 中文文档 v8.0.0 | ||
Node.js API 中文文档 v8.1.0 | ||
|
||
http://nodejs.cn/api/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
|
||
> Stability: 2 - Stable | ||
|
||
<!--name=fs--> | ||
|
||
File I/O is provided by simple wrappers around standard POSIX functions. To | ||
use this module do `require('fs')`. All the methods have asynchronous and | ||
synchronous forms. | ||
|
||
The asynchronous form always takes a completion callback as its last argument. | ||
The arguments passed to the completion callback depend on the method, but the | ||
first argument is always reserved for an exception. If the operation was | ||
completed successfully, then the first argument will be `null` or `undefined`. | ||
|
||
When using the synchronous form any exceptions are immediately thrown. | ||
Exceptions may be handled using `try`/`catch`, or they may be allowed to | ||
bubble up. | ||
|
||
Here is an example of the asynchronous version: | ||
|
||
```js | ||
const fs = require('fs'); | ||
fs.unlink('/tmp/hello', (err) => { | ||
if (err) throw err; | ||
console.log('successfully deleted /tmp/hello'); | ||
}); | ||
``` | ||
|
||
Here is the synchronous version: | ||
|
||
```js | ||
const fs = require('fs'); | ||
fs.unlinkSync('/tmp/hello'); | ||
console.log('successfully deleted /tmp/hello'); | ||
``` | ||
|
||
With the asynchronous methods there is no guaranteed ordering. So the | ||
following is prone to error: | ||
|
||
```js | ||
fs.rename('/tmp/hello', '/tmp/world', (err) => { | ||
if (err) throw err; | ||
console.log('renamed complete'); | ||
}); | ||
fs.stat('/tmp/world', (err, stats) => { | ||
if (err) throw err; | ||
console.log(`stats: ${JSON.stringify(stats)}`); | ||
}); | ||
``` | ||
|
||
It could be that `fs.stat` is executed before `fs.rename`. | ||
The correct way to do this is to chain the callbacks. | ||
|
||
```js | ||
fs.rename('/tmp/hello', '/tmp/world', (err) => { | ||
if (err) throw err; | ||
fs.stat('/tmp/world', (err, stats) => { | ||
if (err) throw err; | ||
console.log(`stats: ${JSON.stringify(stats)}`); | ||
}); | ||
}); | ||
``` | ||
|
||
In busy processes, the programmer is _strongly encouraged_ to use the | ||
asynchronous versions of these calls. The synchronous versions will block | ||
the entire process until they complete--halting all connections. | ||
|
||
The relative path to a filename can be used. Remember, however, that this path | ||
will be relative to `process.cwd()`. | ||
|
||
While it is not recommended, most fs functions allow the callback argument to | ||
be omitted, in which case a default callback is used that rethrows errors. To | ||
get a trace to the original call site, set the `NODE_DEBUG` environment | ||
variable: | ||
|
||
*Note*: Omitting the callback function on asynchronous fs functions is | ||
deprecated and may result in an error being thrown in the future. | ||
|
||
```txt | ||
$ cat script.js | ||
function bad() { | ||
require('fs').readFile('/'); | ||
} | ||
bad(); | ||
$ env NODE_DEBUG=fs node script.js | ||
fs.js:88 | ||
throw backtrace; | ||
^ | ||
Error: EISDIR: illegal operation on a directory, read | ||
<stack trace.> | ||
``` | ||
|
||
*Note:* On Windows Node.js follows the concept of per-drive working directory. | ||
This behavior can be observed when using a drive path without a backslash. For | ||
example `fs.readdirSync('c:\\')` can potentially return a different result than | ||
`fs.readdirSync('c:')`. For more information, see | ||
[this MSDN page][MSDN-Rel-Path]. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
|
||
* `asyncId` {number} | ||
|
||
Called immediately after the callback specified in `before` is completed. | ||
|
||
*Note:* If an uncaught exception occurs during execution of the callback then | ||
`after` will run after the `'uncaughtException'` event is emitted or a | ||
`domain`'s handler runs. | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
|
||
> Stability: 1 - Experimental | ||
|
||
The `async_hooks` module provides an API to register callbacks tracking the | ||
lifetime of asynchronous resources created inside a Node.js application. | ||
It can be accessed using: | ||
|
||
```js | ||
const async_hooks = require('async_hooks'); | ||
``` | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
|
||
<!-- YAML | ||
added: v8.1.0 | ||
--> | ||
|
||
* `callbacks` {Object} the callbacks to register | ||
* Returns: `{AsyncHook}` instance used for disabling and enabling hooks | ||
|
||
Registers functions to be called for different lifetime events of each async | ||
operation. | ||
|
||
The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the | ||
respective asynchronous event during a resource's lifetime. | ||
|
||
All callbacks are optional. So, for example, if only resource cleanup needs to | ||
be tracked then only the `destroy` callback needs to be passed. The | ||
specifics of all functions that can be passed to `callbacks` is in the section | ||
[`Hook Callbacks`][]. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
|
||
* Returns {number} the `asyncId` of the current execution context. Useful to track | ||
when something calls. | ||
|
||
For example: | ||
|
||
```js | ||
console.log(async_hooks.currentId()); // 1 - bootstrap | ||
fs.open(path, 'r', (err, fd) => { | ||
console.log(async_hooks.currentId()); // 6 - open() | ||
}); | ||
``` | ||
|
||
It is important to note that the ID returned fom `currentId()` is related to | ||
execution timing, not causality (which is covered by `triggerId()`). For | ||
example: | ||
|
||
```js | ||
const server = net.createServer(function onConnection(conn) { | ||
// Returns the ID of the server, not of the new connection, because the | ||
// onConnection callback runs in the execution scope of the server's | ||
// MakeCallback(). | ||
async_hooks.currentId(); | ||
}).listen(port, function onListening() { | ||
// Returns the ID of a TickObject (i.e. process.nextTick()) because all | ||
// callbacks passed to .listen() are wrapped in a nextTick(). | ||
async_hooks.currentId(); | ||
}); | ||
``` | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
|
||
* Returns {number} the ID of the resource responsible for calling the callback | ||
that is currently being executed. | ||
|
||
For example: | ||
|
||
```js | ||
const server = net.createServer((conn) => { | ||
// The resource that caused (or triggered) this callback to be called | ||
// was that of the new connection. Thus the return value of triggerId() | ||
// is the asyncId of "conn". | ||
async_hooks.triggerId(); | ||
}).listen(port, () => { | ||
// Even though all callbacks passed to .listen() are wrapped in a nextTick() | ||
// the callback itself exists because the call to the server's .listen() | ||
// was made. So the return value would be the ID of the server. | ||
async_hooks.triggerId(); | ||
}); | ||
``` | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
|
||
* Returns {AsyncHook} A reference to `asyncHook`. | ||
|
||
Disable the callbacks for a given `AsyncHook` instance from the global pool of | ||
AsyncHook callbacks to be executed. Once a hook has been disabled it will not | ||
be called again until enabled. | ||
|
||
For API consistency `disable()` also returns the `AsyncHook` instance. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
|
||
* Returns {AsyncHook} A reference to `asyncHook`. | ||
|
||
Enable the callbacks for a given `AsyncHook` instance. If no callbacks are | ||
provided enabling is a noop. | ||
|
||
The `AsyncHook` instance is by default disabled. If the `AsyncHook` instance | ||
should be enabled immediately after creation, the following pattern can be used. | ||
|
||
```js | ||
const async_hooks = require('async_hooks'); | ||
const hook = async_hooks.createHook(callbacks).enable(); | ||
``` | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
|
||
Below is another example with additional information about the calls to | ||
`init` between the `before` and `after` calls, specifically what the | ||
callback to `listen()` will look like. The output formatting is slightly more | ||
elaborate to make calling context easier to see. | ||
|
||
```js | ||
let indent = 0; | ||
async_hooks.createHook({ | ||
init(asyncId, type, triggerId) { | ||
const cId = async_hooks.currentId(); | ||
const indentStr = ' '.repeat(indent); | ||
fs.writeSync( | ||
1, | ||
`${indentStr}${type}(${asyncId}): trigger: ${triggerId} scope: ${cId}\n`); | ||
}, | ||
before(asyncId) { | ||
const indentStr = ' '.repeat(indent); | ||
fs.writeSync(1, `${indentStr}before: ${asyncId}\n`); | ||
indent += 2; | ||
}, | ||
after(asyncId) { | ||
indent -= 2; | ||
const indentStr = ' '.repeat(indent); | ||
fs.writeSync(1, `${indentStr}after: ${asyncId}\n`); | ||
}, | ||
destroy(asyncId) { | ||
const indentStr = ' '.repeat(indent); | ||
fs.writeSync(1, `${indentStr}destroy: ${asyncId}\n`); | ||
}, | ||
}).enable(); | ||
require('net').createServer(() => {}).listen(8080, () => { | ||
// Let's wait 10ms before logging the server started. | ||
setTimeout(() => { | ||
console.log('>>>', async_hooks.currentId()); | ||
}, 10); | ||
}); | ||
``` | ||
|
||
Output from only starting the server: | ||
|
||
``` | ||
TCPWRAP(2): trigger: 1 scope: 1 | ||
TickObject(3): trigger: 2 scope: 1 | ||
before: 3 | ||
Timeout(4): trigger: 3 scope: 3 | ||
TIMERWRAP(5): trigger: 3 scope: 3 | ||
after: 3 | ||
destroy: 3 | ||
before: 5 | ||
before: 4 | ||
TTYWRAP(6): trigger: 4 scope: 4 | ||
SIGNALWRAP(7): trigger: 4 scope: 4 | ||
TTYWRAP(8): trigger: 4 scope: 4 | ||
>>> 4 | ||
TickObject(9): trigger: 4 scope: 4 | ||
after: 4 | ||
after: 5 | ||
before: 9 | ||
after: 9 | ||
destroy: 4 | ||
destroy: 9 | ||
destroy: 5 | ||
``` | ||
|
||
*Note*: As illustrated in the example, `currentId()` and `scope` each specify | ||
the value of the current execution context; which is delineated by calls to | ||
`before` and `after`. | ||
|
||
Only using `scope` to graph resource allocation results in the following: | ||
|
||
``` | ||
TTYWRAP(6) -> Timeout(4) -> TIMERWRAP(5) -> TickObject(3) -> root(1) | ||
``` | ||
|
||
The `TCPWRAP` isn't part of this graph; even though it was the reason for | ||
`console.log()` being called. This is because binding to a port without a | ||
hostname is actually synchronous, but to maintain a completely asynchronous API | ||
the user's callback is placed in a `process.nextTick()`. | ||
The graph only shows *when* a resource was created, not *why*, so to track | ||
the *why* use `triggerId`. | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
|
||
* Returns {number} the unique `asyncId` assigned to the resource. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
|
||
* Returns {undefined} | ||
|
||
Call all `after` callbacks. If nested calls to `emitBefore()` were made, then | ||
make sure the stack is unwound properly. Otherwise an error will be thrown. | ||
|
||
If the user's callback throws an exception then `emitAfter()` will | ||
automatically be called for all `asyncId`s on the stack if the error is handled by | ||
a domain or `'uncaughtException'` handler. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
|
||
* Returns {undefined} | ||
|
||
Call all `before` callbacks and let them know a new asynchronous execution | ||
context is being entered. If nested calls to `emitBefore()` are made, the stack | ||
of `asyncId`s will be tracked and properly unwound. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
|
||
* Returns {undefined} | ||
|
||
Call all `destroy` hooks. This should only ever be called once. An error will | ||
be thrown if it is called more than once. This **must** be manually called. If | ||
the resource is left to be collected by the GC then the `destroy` hooks will | ||
never be called. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
|
||
* Returns {number} the same `triggerId` that is passed to the `AsyncResource` | ||
constructor. | ||
|
||
[`Hook Callbacks`]: #hook-callbacks |
Oops, something went wrong.