diff --git a/addons/c_addons.md b/addons/c_addons.md index 986a998c..823b9ab3 100644 --- a/addons/c_addons.md +++ b/addons/c_addons.md @@ -7,7 +7,7 @@ 插件提供了 JavaScript 和 C/C++ 库之间的接口。 实现插件有三种选择:N-API、nan、或直接使用内部的 V8、libuv 和 Node.js 库。 -除非你需要直接访问 N-API 未公开的函数,否则请使用 N-API。 +除非需要直接访问 N-API 未公开的函数,否则请使用 N-API。 有关 N-API 的更多信息,参阅[具有 N-API 的 C/C++ 插件][_n-api]。 当不使用 N-API 时,实现插件很复杂,涉及多个组件和 API 的知识: diff --git a/addons/context_aware_addons.md b/addons/context_aware_addons.md index 5d0c2eb1..7b73204e 100644 --- a/addons/context_aware_addons.md +++ b/addons/context_aware_addons.md @@ -32,11 +32,19 @@ NODE_MODULE_INITIALIZER(Local exports, 可以通过执行以下步骤来构造上下文感知的插件以避免全局静态数据: -* 定义一个持有每个插件实例数据的类。这样的类应该包含一个 `v8::Global` 持有 `exports` 对象的弱引用。与该弱引用关联的回调函数将会破坏该类的实例。 -* 在插件实例化过程中构造这个类的实例,把`v8::Global` 挂到 `exports` 对象上去。 -* 在 `v8::External` 中保存这个类的实例。 -* 通过将 `v8::External` 传给 `v8::FunctionTemplate` 构造函数,该函数会创建本地支持的 JavaScript 函数,把 `v8::External` 传递给所有暴露给 JavaScript 的方法。 - `v8::FunctionTemplate` 构造函数的第三个参数接受 `v8::External`。 +* 定义一个类,该类会保存每个插件实例的数据,并且具有以下形式的静态成员: + ```C++ + static void DeleteInstance(void* data) { + // 将 `data` 转换为该类的实例并删除它。 + } + ``` +* 在插件的初始化过程中堆分配此类的实例。 + 这可以使用 `new` 关键字来完成。 +* 调用 `node::AddEnvironmentCleanupHook()`,将上面创建的实例和指向 `DeleteInstance()` 的指针传给它。 + 这可以确保实例会在销毁环境之后被删除。 +* 将类的实例保存在 `v8::External`中。 +* 通过将 `v8::External` 传给 `v8::FunctionTemplate::New()` 或 `v8::Function::New()`(用以创建原生支持的 JavaScript 函数)来将其传给暴露给 JavaScript 的所有方法。 + `v8::FunctionTemplate::New()` 或 `v8::Function::New()` 的第三个参数接受 `v8::External`,并使用 `v8::FunctionCallbackInfo::Data()` 方法使其在原生回调中可用。 这确保了每个扩展实例数据到达每个能被 JavaScript 访问的绑定。每个扩展实例数据也必须通过其创建的任何异步回调函数。 @@ -49,24 +57,18 @@ using namespace v8; class AddonData { public: - AddonData(Isolate* isolate, Local exports): + explicit AddonData(Isolate* isolate): call_count(0) { - // 将次对象的实例挂到 exports 上。 - exports_.Reset(isolate, exports); - exports_.SetWeak(this, DeleteMe, WeakCallbackType::kParameter); + // 确保在清理环境时删除每个插件实例的数据。 + node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this); } // 每个插件的数据。 int call_count; - private: - // 导出即将被回收时调用的方法。 - static void DeleteMe(const WeakCallbackInfo& info) { - delete info.GetParameter(); + static void DeleteInstance(void* data) { + delete static_cast(data); } - - // 导出对象弱句柄。该类的实例将与其若绑定的 exports 对象一起销毁。 - v8::Global exports_; }; static void Method(const v8::FunctionCallbackInfo& info) { @@ -81,12 +83,13 @@ static void Method(const v8::FunctionCallbackInfo& info) { NODE_MODULE_INIT(/* exports, module, context */) { Isolate* isolate = context->GetIsolate(); - // 为该扩展实例的AddonData创建一个新的实例 + // 为此插件实例创建一个新的 `AddonData` 实例,并将其生命周期与 Node.js 环境的生命周期联系起来。 AddonData* data = new AddonData(isolate, exports); - // 在 v8::External 中包裹数据,这样我们就可以将它传递给我们暴露的方法。 + // 在 `v8::External` 中包裹数据,这样我们就可以将它传递给我们暴露的方法。 Local external = External::New(isolate, data); - // 把 "Method" 方法暴露给 JavaScript,并确保其接收我们通过把 `external` 作为 FunctionTemplate 构造函数第三个参数时创建的每个插件实例的数据。 + // 把 `Method` 方法暴露给 JavaScript, + // 并确保其接收我们通过把 `external` 作为 `FunctionTemplate` 构造函数第三个参数时创建的每个插件实例的数据。 exports->Set(context, String::NewFromUtf8(isolate, "method", NewStringType::kNormal) .ToLocalChecked(), diff --git a/assert/assert_deepequal_actual_expected_message.md b/assert/assert_deepequal_actual_expected_message.md index be560bea..80b5b69e 100644 --- a/assert/assert_deepequal_actual_expected_message.md +++ b/assert/assert_deepequal_actual_expected_message.md @@ -1,6 +1,10 @@ * `string` {string} diff --git a/assert/assert_equal_actual_expected_message.md b/assert/assert_equal_actual_expected_message.md index 4389d04b..87719a4a 100644 --- a/assert/assert_equal_actual_expected_message.md +++ b/assert/assert_equal_actual_expected_message.md @@ -1,5 +1,10 @@ * `actual` {any} @@ -15,7 +20,8 @@ An alias of [`assert.strictEqual()`][]. > Stability: 0 - Deprecated: Use [`assert.strictEqual()`][] instead. Tests shallow, coercive equality between the `actual` and `expected` parameters -using the [Abstract Equality Comparison][] ( `==` ). +using the [Abstract Equality Comparison][] ( `==` ). `NaN` is special handled +and treated as being identical in case both sides are `NaN`. ```js const assert = require('assert'); @@ -24,6 +30,8 @@ assert.equal(1, 1); // OK, 1 == 1 assert.equal(1, '1'); // OK, 1 == '1' +assert.equal(NaN, NaN); +// OK assert.equal(1, 2); // AssertionError: 1 == 2 diff --git a/assert/assert_match_string_regexp_message.md b/assert/assert_match_string_regexp_message.md index 6f91cf15..328ede3c 100644 --- a/assert/assert_match_string_regexp_message.md +++ b/assert/assert_match_string_regexp_message.md @@ -1,5 +1,5 @@ * `string` {string} diff --git a/assert/assert_notdeepequal_actual_expected_message.md b/assert/assert_notdeepequal_actual_expected_message.md index 17649f43..604e03f9 100644 --- a/assert/assert_notdeepequal_actual_expected_message.md +++ b/assert/assert_notdeepequal_actual_expected_message.md @@ -1,6 +1,10 @@ * `actual` {any} @@ -15,7 +20,8 @@ An alias of [`assert.notStrictEqual()`][]. > Stability: 0 - Deprecated: Use [`assert.notStrictEqual()`][] instead. Tests shallow, coercive inequality with the [Abstract Equality Comparison][] -( `!=` ). +(`!=` ). `NaN` is special handled and treated as being identical in case both +sides are `NaN`. ```js const assert = require('assert'); diff --git a/assert/comparison_details.md b/assert/comparison_details.md index 29e1d8b7..39f44ab3 100644 --- a/assert/comparison_details.md +++ b/assert/comparison_details.md @@ -1,5 +1,5 @@ -* 使用[抽象的相等性比较][Abstract Equality Comparison]来比较原始值。 +* 除 `NaN` 之外,使用[抽象的相等性比较][Abstract Equality Comparison](`==`)来比较原始值。如果双方均为 `NaN`,则视为相同。 * 对象的[类型标签][Object.prototype.toString()]应该相同。 * 只考虑[可枚举的自身属性][enumerable "own" properties]。 * 始终比较 [`Error`] 的名称和消息,即使这些不是可枚举的属性。 diff --git a/assert/strict_assertion_mode.md b/assert/strict_assertion_mode.md index cd5fd09a..0ba7edf5 100644 --- a/assert/strict_assertion_mode.md +++ b/assert/strict_assertion_mode.md @@ -1,7 +1,7 @@ + +* Returns: {Object} The resource representing the current execution. + Useful to store data within the resource. + +Resource objects returned by `executionAsyncResource()` are most often internal +Node.js handle objects with undocumented APIs. Using any functions or properties +on the object is likely to crash your application and should be avoided. + +Using `executionAsyncResource()` in the top-level execution context will +return an empty object as there is no handle or request object to use, +but having an object representing the top-level can be helpful. + +```js +const { open } = require('fs'); +const { executionAsyncId, executionAsyncResource } = require('async_hooks'); + +console.log(executionAsyncId(), executionAsyncResource()); // 1 {} +open(__filename, 'r', (err, fd) => { + console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap +}); +``` + +This can be used to implement continuation local storage without the +use of a tracking `Map` to store the metadata: + +```js +const { createServer } = require('http'); +const { + executionAsyncId, + executionAsyncResource, + createHook +} = require('async_hooks'); +const sym = Symbol('state'); // Private symbol to avoid pollution + +createHook({ + init(asyncId, type, triggerAsyncId, resource) { + const cr = executionAsyncResource(); + if (cr) { + resource[sym] = cr[sym]; + } + } +}).enable(); + +const server = createServer(function(req, res) { + executionAsyncResource()[sym] = { state: req.url }; + setTimeout(function() { + res.end(JSON.stringify(executionAsyncResource()[sym])); + }, 100); +}).listen(3000); +``` + diff --git a/async_hooks/asynclocalstorage_disable.md b/async_hooks/asynclocalstorage_disable.md new file mode 100644 index 00000000..4a002508 --- /dev/null +++ b/async_hooks/asynclocalstorage_disable.md @@ -0,0 +1,19 @@ + + +This method disables the instance of `AsyncLocalStorage`. All subsequent calls +to `asyncLocalStorage.getStore()` will return `undefined` until +`asyncLocalStorage.run()` is called again. + +When calling `asyncLocalStorage.disable()`, all current contexts linked to the +instance will be exited. + +Calling `asyncLocalStorage.disable()` is required before the +`asyncLocalStorage` can be garbage collected. This does not apply to stores +provided by the `asyncLocalStorage`, as those objects are garbage collected +along with the corresponding async resources. + +This method is to be used when the `asyncLocalStorage` is not in use anymore +in the current process. + diff --git a/async_hooks/asynclocalstorage_enterwith_store.md b/async_hooks/asynclocalstorage_enterwith_store.md new file mode 100644 index 00000000..3d4c1710 --- /dev/null +++ b/async_hooks/asynclocalstorage_enterwith_store.md @@ -0,0 +1,41 @@ + + +* `store` {any} + +Calling `asyncLocalStorage.enterWith(store)` will transition into the context +for the remainder of the current synchronous execution and will persist +through any following asynchronous calls. + +Example: + +```js +const store = { id: 1 }; +asyncLocalStorage.enterWith(store); +asyncLocalStorage.getStore(); // Returns the store object +someAsyncOperation(() => { + asyncLocalStorage.getStore(); // Returns the same object +}); +``` + +This transition will continue for the _entire_ synchronous execution. +This means that if, for example, the context is entered within an event +handler subsequent event handlers will also run within that context unless +specifically bound to another context with an `AsyncResource`. + +```js +const store = { id: 1 }; + +emitter.on('my-event', () => { + asyncLocalStorage.enterWith(store); +}); +emitter.on('my-event', () => { + asyncLocalStorage.getStore(); // Returns the same object +}); + +asyncLocalStorage.getStore(); // Returns undefined +emitter.emit('my-event'); +asyncLocalStorage.getStore(); // Returns the same object +``` + diff --git a/async_hooks/asynclocalstorage_exit_callback_args.md b/async_hooks/asynclocalstorage_exit_callback_args.md new file mode 100644 index 00000000..71153f5d --- /dev/null +++ b/async_hooks/asynclocalstorage_exit_callback_args.md @@ -0,0 +1,34 @@ + + +* `callback` {Function} +* `...args` {any} + +This methods runs a function synchronously outside of a context and return its +return value. The store is not accessible within the callback function or +the asynchronous operations created within the callback. + +Optionally, arguments can be passed to the function. They will be passed to +the callback function. + +If the callback function throws an error, it will be thrown by `exit` too. +The stacktrace will not be impacted by this call and +the context will be re-entered. + +Example: + +```js +// Within a call to run +try { + asyncLocalStorage.getStore(); // Returns the store object or value + asyncLocalStorage.exit(() => { + asyncLocalStorage.getStore(); // Returns undefined + throw new Error(); + }); +} catch (e) { + asyncLocalStorage.getStore(); // Returns the same object or value + // The error will be caught here +} +``` + diff --git a/async_hooks/asynclocalstorage_getstore.md b/async_hooks/asynclocalstorage_getstore.md new file mode 100644 index 00000000..5aeeb67a --- /dev/null +++ b/async_hooks/asynclocalstorage_getstore.md @@ -0,0 +1,10 @@ + + +* Returns: {any} + +This method returns the current store. +If this method is called outside of an asynchronous context initialized by +calling `asyncLocalStorage.run`, it will return `undefined`. + diff --git a/async_hooks/asynclocalstorage_run_store_callback_args.md b/async_hooks/asynclocalstorage_run_store_callback_args.md new file mode 100644 index 00000000..738d4e8f --- /dev/null +++ b/async_hooks/asynclocalstorage_run_store_callback_args.md @@ -0,0 +1,34 @@ + + +* `store` {any} +* `callback` {Function} +* `...args` {any} + +This methods runs a function synchronously within a context and return its +return value. The store is not accessible outside of the callback function or +the asynchronous operations created within the callback. + +Optionally, arguments can be passed to the function. They will be passed to +the callback function. + +If the callback function throws an error, it will be thrown by `run` too. +The stacktrace will not be impacted by this call and the context will +be exited. + +Example: + +```js +const store = { id: 2 }; +try { + asyncLocalStorage.run(store, () => { + asyncLocalStorage.getStore(); // Returns the store object + throw new Error(); + }); +} catch (e) { + asyncLocalStorage.getStore(); // Returns undefined + // The error will be caught here +} +``` + diff --git a/async_hooks/class_asynchook.md b/async_hooks/class_asynchook.md new file mode 100644 index 00000000..18c5ca18 --- /dev/null +++ b/async_hooks/class_asynchook.md @@ -0,0 +1,4 @@ + +The class `AsyncHook` exposes an interface for tracking lifetime events +of asynchronous operations. + diff --git a/async_hooks/class_asynclocalstorage.md b/async_hooks/class_asynclocalstorage.md new file mode 100644 index 00000000..ba453540 --- /dev/null +++ b/async_hooks/class_asynclocalstorage.md @@ -0,0 +1,48 @@ + + +This class is used to create asynchronous state within callbacks and promise +chains. It allows storing data throughout the lifetime of a web request +or any other asynchronous duration. It is similar to thread-local storage +in other languages. + +The following example uses `AsyncLocalStorage` to build a simple logger +that assigns IDs to incoming HTTP requests and includes them in messages +logged within each request. + +```js +const http = require('http'); +const { AsyncLocalStorage } = require('async_hooks'); + +const asyncLocalStorage = new AsyncLocalStorage(); + +function logWithId(msg) { + const id = asyncLocalStorage.getStore(); + console.log(`${id !== undefined ? id : '-'}:`, msg); +} + +let idSeq = 0; +http.createServer((req, res) => { + asyncLocalStorage.run(idSeq++, () => { + logWithId('start'); + // Imagine any chain of async operations here + setImmediate(() => { + logWithId('finish'); + res.end(); + }); + }); +}).listen(8080); + +http.get('http://localhost:8080'); +http.get('http://localhost:8080'); +// Prints: +// 0: start +// 1: start +// 0: finish +// 1: finish +``` + +When having multiple instances of `AsyncLocalStorage`, they are independent +from each other. It is safe to instantiate this class multiple times. + diff --git a/async_hooks/new_asynclocalstorage.md b/async_hooks/new_asynclocalstorage.md new file mode 100644 index 00000000..9f07f8fc --- /dev/null +++ b/async_hooks/new_asynclocalstorage.md @@ -0,0 +1,7 @@ + + +Creates a new instance of `AsyncLocalStorage`. Store is only provided within a +`run` method call. + diff --git a/async_hooks/new_asyncresource_type_options.md b/async_hooks/new_asyncresource_type_options.md index f29d678a..b2a6a89a 100644 --- a/async_hooks/new_asyncresource_type_options.md +++ b/async_hooks/new_asyncresource_type_options.md @@ -3,10 +3,12 @@ * `options` {Object} * `triggerAsyncId` {number} The ID of the execution context that created this async event. **Default:** `executionAsyncId()`. - * `requireManualDestroy` {boolean} Disables automatic `emitDestroy` when the - object is garbage collected. This usually does not need to be set (even if - `emitDestroy` is called manually), unless the resource's `asyncId` is - retrieved and the sensitive API's `emitDestroy` is called with it. + * `requireManualDestroy` {boolean} If set to `true`, disables `emitDestroy` + when the object is garbage collected. This usually does not need to be set + (even if `emitDestroy` is called manually), unless the resource's `asyncId` + is retrieved and the sensitive API's `emitDestroy` is called with it. + When set to `false`, the `emitDestroy` call on garbage collection + will only take place if there is at least one active `destroy` hook. **Default:** `false`. Example usage: diff --git a/async_hooks/usage_with_async_await.md b/async_hooks/usage_with_async_await.md new file mode 100644 index 00000000..bff095fe --- /dev/null +++ b/async_hooks/usage_with_async_await.md @@ -0,0 +1,26 @@ + +If, within an async function, only one `await` call is to run within a context, +the following pattern should be used: + +```js +async function fn() { + await asyncLocalStorage.run(new Map(), () => { + asyncLocalStorage.getStore().set('key', value); + return foo(); // The return value of foo will be awaited + }); +} +``` + +In this example, the store is only available in the callback function and the +functions called by `foo`. Outside of `run`, calling `getStore` will return +`undefined`. + + + + + + + + + + diff --git a/async_hooks/using_asyncresource_for_a_worker_thread_pool.md b/async_hooks/using_asyncresource_for_a_worker_thread_pool.md index d1ba9033..f1fe4520 100644 --- a/async_hooks/using_asyncresource_for_a_worker_thread_pool.md +++ b/async_hooks/using_asyncresource_for_a_worker_thread_pool.md @@ -118,12 +118,3 @@ for (let i = 0; i < 10; i++) { } ``` - - - - - - - - - diff --git a/buffer/buf_byteoffset.md b/buffer/buf_byteoffset.md index 741d79ce..9685e834 100644 --- a/buffer/buf_byteoffset.md +++ b/buffer/buf_byteoffset.md @@ -3,15 +3,16 @@ 当 `Buffer.from(ArrayBuffer, byteOffset, length)` 设置了 `byteOffset` 或创建一个小于 `Buffer.poolSize` 的 buffer 时,底层的 `ArrayBuffer` 的偏移量并不是从 0 开始。 -当直接使用 `buf.buffer` 访问底层的 `ArrayBuffer` 时,`ArrayBuffer` 的第一个字节可能并不指向 `buf` 对象。 +当直接使用 `buf.buffer` 访问底层的 `ArrayBuffer` 时可能会导致问题,因为 `ArrayBuffer` 的其他部分可能并不指向 `buf` 对象。 -所有使用 `Buffer` 对象创建 `TypedArray` 对象时,需要正确地指定 `byteOffset`。 +当创建与 `Buffer` 共享其内存的 `TypedArray` 对象时,需要正确地指定 `byteOffset`。 ```js // 创建一个小于 `Buffer.poolSize` 的 buffer。 const nodeBuffer = new Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); -// 当将 Node.js Buffer 赋值给一个 Int8 的 TypedArray 时,记得使用 byteOffset。 +// 当将 Node.js Buffer 转换为 Int8Array 时, +// 应使用 byteOffset 仅引用 `nodeBuffer.buffer` 中包含 `nodeBuffer` 内存的部分。 new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length); ``` diff --git a/buffer/buf_copy_target_targetstart_sourcestart_sourceend.md b/buffer/buf_copy_target_targetstart_sourcestart_sourceend.md index 4d424141..fb67466b 100644 --- a/buffer/buf_copy_target_targetstart_sourcestart_sourceend.md +++ b/buffer/buf_copy_target_targetstart_sourcestart_sourceend.md @@ -10,6 +10,8 @@ added: v0.1.90 拷贝 `buf` 中某个区域的数据到 `target` 中的某个区域,即使 `target` 的内存区域与 `buf` 的重叠。 +[`TypedArray#set()`] 执行相同的操作,并且可用于所有的 TypedArray,包括 Node.js 的 Buffer,尽管它采用不同的函数参数。 + ```js // 创建两个 `Buffer` 实例。 const buf1 = Buffer.allocUnsafe(26); @@ -22,6 +24,8 @@ for (let i = 0; i < 26; i++) { // 拷贝 `buf1` 中第 16 至 19 字节偏移量的数据到 `buf2` 第 8 字节偏移量开始。 buf1.copy(buf2, 8, 16, 20); +// 这等效于: +// buf2.set(buf1.subarray(16, 20), 8); console.log(buf2.toString('ascii', 0, 25)); // 打印: !!!!!!!!qrst!!!!!!!!!!!!! diff --git a/buffer/buf_equals_otherbuffer.md b/buffer/buf_equals_otherbuffer.md index be312442..6032a5bf 100644 --- a/buffer/buf_equals_otherbuffer.md +++ b/buffer/buf_equals_otherbuffer.md @@ -10,7 +10,7 @@ changes: * 返回: {boolean} 如果 `buf` 与 `otherBuffer` 具有完全相同的字节,则返回 `true`,否则返回 `false`。 - +相当于 [`buf.compare(otherBuffer) === 0`][`buf.compare()`]。 ```js const buf1 = Buffer.from('ABC'); diff --git a/buffer/buf_fill_value_offset_end_encoding.md b/buffer/buf_fill_value_offset_end_encoding.md index 04f4a6fb..77ce3715 100644 --- a/buffer/buf_fill_value_offset_end_encoding.md +++ b/buffer/buf_fill_value_offset_end_encoding.md @@ -44,10 +44,10 @@ console.log(b.toString()); 如果 `fill()` 最后写入的是一个多字节字符,则只写入适合 `buf` 的字节: ```js -// 用一个双字节字符填充 `Buffer`。 +// 使用在 UTF-8 中占用两个字节的字符来填充 `Buffer`。 -console.log(Buffer.allocUnsafe(3).fill('\u0222')); -// 打印: +console.log(Buffer.allocUnsafe(5).fill('\u0222')); +// 打印: ``` 如果 `value` 包含无效的字符,则截掉无效的字符。 diff --git a/buffer/buf_index.md b/buffer/buf_index.md index 9475340d..22570687 100644 --- a/buffer/buf_index.md +++ b/buffer/buf_index.md @@ -8,11 +8,12 @@ name: [index] 索引操作符 `[index]` 可用于获取或设置 `buf` 中指定的 `index` 位置的八位字节。 该值指向单个字节,所以有效的值的范围是 `0x00` 至 `0xFF`(十六进制)、或 `0` 至 `255`(十进制)。 -该操作符继承自 `Uint8Array`,所以对越界访问的行为与 `UInt8Array` 相同。 -也就是说,取值时返回 `undefined`,赋值时不作为。 +该操作符继承自 `Uint8Array`,所以对越界访问的行为与 `Uint8Array` 相同。 +也就是说,当 `index` 为负数或 `>= buf.length` 时,则 `buf[index]` 返回 `undefined`,而如果 `index` 为负数或 `>= buf.length` 时,则 `buf[index] = value` 不会修改该 buffer。 ```js // 拷贝 ASCII 字符串到 `Buffer`,每次拷贝一个字节。 +// (这仅适用于只有 ASCII 字符串。通常,应使用 `Buffer.from()` 来执行此转换。) const str = 'http://nodejs.cn/'; const buf = Buffer.allocUnsafe(str.length); @@ -21,7 +22,7 @@ for (let i = 0; i < str.length; i++) { buf[i] = str.charCodeAt(i); } -console.log(buf.toString('ascii')); +console.log(buf.toString('utf8')); // 打印: http://nodejs.cn/ ``` diff --git a/buffer/buf_length.md b/buffer/buf_length.md index 11acc91f..44367826 100644 --- a/buffer/buf_length.md +++ b/buffer/buf_length.md @@ -4,37 +4,18 @@ added: v0.1.90 * {integer} -返回内存中分配给 `buf` 的字节数。 -不一定反映 `buf` 中可用数据的字节量。 +返回 `buf` 中的字节数。 ```js -// 创建一个 `Buffer`,并写入一个 ASCII 字符串。 +// 创建一个 `Buffer`,并使用 UTF-8 写入一个短的字符串。 const buf = Buffer.alloc(1234); console.log(buf.length); // 打印: 1234 -buf.write('http://nodejs.cn/', 0, 'ascii'); +buf.write('http://nodejs.cn/', 0, 'utf8'); console.log(buf.length); // 打印: 1234 ``` - -虽然 `length` 属性不是不可变的,但改变 `length` 的值可能会造成不确定的结果。 -如果想改变一个 `Buffer` 的长度,应该将 `length` 视为只读的,且使用 [`buf.slice()`] 创建一个新的 `Buffer`。 - -```js -let buf = Buffer.allocUnsafe(10); - -buf.write('abcdefghj', 0, 'ascii'); - -console.log(buf.length); -// 打印: 10 - -buf = buf.slice(0, 5); - -console.log(buf.length); -// 打印: 5 -``` - diff --git a/buffer/buf_readbigint64le_offset.md b/buffer/buf_readbigint64le_offset.md index ff06d314..b3e0190c 100644 --- a/buffer/buf_readbigint64le_offset.md +++ b/buffer/buf_readbigint64le_offset.md @@ -5,7 +5,7 @@ added: v12.0.0 * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 * 返回: {bigint} -用指定的字节序格式(`readBigInt64BE()` 返回大端序,`readBigInt64LE()` 返回小端序)从 `buf` 中指定的 `offset` 读取一个有符号的 64 位整数值。 +用指定的[字节序][endianness](`readBigInt64BE()` 读取为大端序,`readBigInt64LE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个有符号的 64 位整数值。 从 `Buffer` 中读取的整数值会被解析为二进制补码值。 diff --git a/buffer/buf_readbiguint64le_offset.md b/buffer/buf_readbiguint64le_offset.md index 868b10a4..6a4d09f3 100644 --- a/buffer/buf_readbiguint64le_offset.md +++ b/buffer/buf_readbiguint64le_offset.md @@ -5,7 +5,7 @@ added: v12.0.0 * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 * 返回: {bigint} -用指定的字节序格式(`readBigUInt64BE()` 返回大端序,`readBigUInt64LE()` 返回小端序)从 `buf` 中指定的 `offset` 读取一个无符号的 64 位整数值。 +用指定的[字节序][endianness](`readBigUInt64BE()` 读取为大端序,`readBigUInt64LE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个无符号的 64 位整数值。 ```js const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); diff --git a/buffer/buf_readdoublele_offset.md b/buffer/buf_readdoublele_offset.md index 056a4ceb..8aaabbc6 100644 --- a/buffer/buf_readdoublele_offset.md +++ b/buffer/buf_readdoublele_offset.md @@ -10,7 +10,7 @@ changes: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 * 返回: {number} -用指定的字节序格式(`readDoubleBE()` 返回大端序,`readDoubleLE()` 返回小端序)从 `buf` 中指定的 `offset` 读取一个 64 位双精度值。 +用指定的[字节序][endianness](`readDoubleBE()` 读取为大端序,`readDoubleLE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个 64 位双精度值。 ```js const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); diff --git a/buffer/buf_readfloatle_offset.md b/buffer/buf_readfloatle_offset.md index f9809909..d1fc12b0 100644 --- a/buffer/buf_readfloatle_offset.md +++ b/buffer/buf_readfloatle_offset.md @@ -10,7 +10,7 @@ changes: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 * 返回: {number} -用指定的字节序格式(`readFloatBE()` 返回大端序,`readFloatLE()` 返回小端序)从 `buf` 中指定的 `offset` 读取一个 32 位浮点值。 +用指定的[字节序][endianness](`readFloatBE()` 读取为大端序,`readFloatLE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个 32 位浮点值。 ```js const buf = Buffer.from([1, 2, 3, 4]); diff --git a/buffer/buf_readint16le_offset.md b/buffer/buf_readint16le_offset.md index e391571f..2ebe5df4 100644 --- a/buffer/buf_readint16le_offset.md +++ b/buffer/buf_readint16le_offset.md @@ -10,7 +10,7 @@ changes: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 2`。**默认值:** `0`。 * 返回: {integer} -用指定的字节序格式(`readInt16BE()` 返回大端序,`readInt16LE()` 返回小端序)从 `buf` 中指定的 `offset` 读取一个有符号的 16 位整数值。 +用指定的[字节序][endianness](`readInt16BE()` 读取为大端序,`readInt16LE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个有符号的 16 位整数值。 从 `Buffer` 中读取的整数值会被解析为二进制补码值。 diff --git a/buffer/buf_readint32le_offset.md b/buffer/buf_readint32le_offset.md index 9b8b5724..fe1c1830 100644 --- a/buffer/buf_readint32le_offset.md +++ b/buffer/buf_readint32le_offset.md @@ -10,7 +10,7 @@ changes: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 * 返回: {integer} -用指定的字节序格式(`readInt32BE()` 返回大端序,`readInt32LE()` 返回小端序)从 `buf` 中指定的 `offset` 读取一个有符号的 32 位整数值。 +用指定的[字节序][endianness](`readInt32BE()` 读取为大端序,`readInt32LE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个有符号的 32 位整数值。 从 `Buffer` 中读取的整数值会被解析为二进制补码值。 diff --git a/buffer/buf_readuint16le_offset.md b/buffer/buf_readuint16le_offset.md index 1262a849..503be0fb 100644 --- a/buffer/buf_readuint16le_offset.md +++ b/buffer/buf_readuint16le_offset.md @@ -10,7 +10,7 @@ changes: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 2`。**默认值:** `0`。 * 返回: {integer} -用指定的字节序格式(`readUInt16BE()` 返回大端序,`readUInt16LE()` 返回小端序)从 `buf` 中指定的 `offset` 读取一个无符号的 16 位整数值。 +用指定的[字节序][endianness](`readUInt16BE()` 读取为大端序,`readUInt16LE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个无符号的 16 位整数值。 ```js const buf = Buffer.from([0x12, 0x34, 0x56]); diff --git a/buffer/buf_readuint32le_offset.md b/buffer/buf_readuint32le_offset.md index a7d9bbc3..bb3732f1 100644 --- a/buffer/buf_readuint32le_offset.md +++ b/buffer/buf_readuint32le_offset.md @@ -10,7 +10,7 @@ changes: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 * 返回: {integer} -用指定的字节序格式(`readUInt32BE()` 返回大端序,`readUInt32LE()` 返回小端序)从 `buf` 中指定的 `offset` 读取一个无符号的 32 位整数值。 +用指定的[字节序][endianness](`readUInt32BE()` 读取为大端序,`readUInt32LE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个无符号的 32 位整数值。 ```js const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); diff --git a/buffer/buf_subarray_start_end.md b/buffer/buf_subarray_start_end.md index cea8a7da..ef3b243f 100644 --- a/buffer/buf_subarray_start_end.md +++ b/buffer/buf_subarray_start_end.md @@ -10,6 +10,8 @@ added: v3.0.0 指定大于 [`buf.length`] 的 `end` 将会返回与 `end` 等于 [`buf.length`] 时相同的结果。 +此方法继承自 [`TypedArray#subarray()`]。 + 修改新的 `Buffer` 切片将会修改原始 `Buffer` 中的内存,因为两个对象分配的内存是重叠的。 ```js diff --git a/buffer/buf_swap64.md b/buffer/buf_swap64.md index f28b9dff..08fcae00 100644 --- a/buffer/buf_swap64.md +++ b/buffer/buf_swap64.md @@ -24,6 +24,4 @@ buf2.swap64(); // 抛出异常 ERR_INVALID_BUFFER_SIZE。 ``` -JavaScript 不能编码 64 位整数。 -该方法是用来处理 64 位浮点数的。 diff --git a/buffer/buf_tojson.md b/buffer/buf_tojson.md index 111e5b92..98514711 100644 --- a/buffer/buf_tojson.md +++ b/buffer/buf_tojson.md @@ -7,6 +7,9 @@ added: v0.9.2 返回 `buf` 的 JSON 格式。 当字符串化 `Buffer` 实例时,[`JSON.stringify()`] 会调用该函数。 +`Buffer.from()` 接受此方法返回的格式的对象。 +特别是,`Buffer.from(buf.toJSON())` 的工作方式类似于 `Buffer.from(buf)`。 + ```js const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); const json = JSON.stringify(buf); @@ -16,7 +19,7 @@ console.log(json); const copy = JSON.parse(json, (key, value) => { return value && value.type === 'Buffer' ? - Buffer.from(value.data) : + Buffer.from(value) : value; }); diff --git a/buffer/buf_tostring_encoding_start_end.md b/buffer/buf_tostring_encoding_start_end.md index f7865c42..f5bcd696 100644 --- a/buffer/buf_tostring_encoding_start_end.md +++ b/buffer/buf_tostring_encoding_start_end.md @@ -9,7 +9,8 @@ added: v0.1.90 根据 `encoding` 指定的字符编码将 `buf` 解码成字符串。 传入 `start` 和 `end` 可以只解码 `buf` 的子集。 -如果输入中的字节序列在给定的 `encoding` 中无效,则将其替换为替换字符 `U+FFFD`。 + +如果 `encoding` 为 `'utf8'`,并且输入中的字节序列不是有效的 UTF-8,则每个无效的字节都会由替换字符 `U+FFFD` 替换。 字符串的最大长度(以 UTF-16 为单位)可查看 [`buffer.constants.MAX_STRING_LENGTH`]。 @@ -21,9 +22,9 @@ for (let i = 0; i < 26; i++) { buf1[i] = i + 97; } -console.log(buf1.toString('ascii')); +console.log(buf1.toString('utf8')); // 打印: abcdefghijklmnopqrstuvwxyz -console.log(buf1.toString('ascii', 0, 5)); +console.log(buf1.toString('utf8', 0, 5)); // 打印: abcde const buf2 = Buffer.from('tést'); diff --git a/buffer/buf_write_string_offset_length_encoding.md b/buffer/buf_write_string_offset_length_encoding.md index 07fb2c36..45093dfc 100644 --- a/buffer/buf_write_string_offset_length_encoding.md +++ b/buffer/buf_write_string_offset_length_encoding.md @@ -4,7 +4,7 @@ added: v0.1.90 * `string` {string} 要写入 `buf` 的字符串。 * `offset` {integer} 开始写入 `string` 之前要跳过的字节数。**默认值:** `0`。 -* `length` {integer} 要写入的字节数。**默认值:** `buf.length - offset`。 +* `length` {integer} 要写入的最大字节数(写入的字节数不会超出 `buf.length - offset`)。**默认值:** `buf.length - offset`。 * `encoding` {string} `string` 的字符编码。**默认值:** `'utf8'`。 * 返回: {integer} 已写入的字节数。 @@ -20,5 +20,12 @@ const len = buf.write('\u00bd + \u00bc = \u00be', 0); console.log(`${len} 个字节: ${buf.toString('utf8', 0, len)}`); // 打印: 12 个字节: ½ + ¼ = ¾ + +const buffer = Buffer.alloc(10); + +const length = buffer.write('abcd', 8); + +console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); +// 打印: 2 个字节 : ab ``` diff --git a/buffer/buf_writebigint64le_value_offset.md b/buffer/buf_writebigint64le_value_offset.md index 482c8e51..e01db3b0 100644 --- a/buffer/buf_writebigint64le_value_offset.md +++ b/buffer/buf_writebigint64le_value_offset.md @@ -6,7 +6,7 @@ added: v12.0.0 * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的字节序格式(`writeBigInt64BE()` 写入大端序,`writeBigInt64LE()` 写入小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +用指定的[字节序][endianness](`writeBigInt64BE()` 写入为大端序,`writeBigInt64LE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 `value` 会被解析并写入为二进制补码的有符号整数。 diff --git a/buffer/buf_writebiguint64le_value_offset.md b/buffer/buf_writebiguint64le_value_offset.md index 7c928915..4d257eca 100644 --- a/buffer/buf_writebiguint64le_value_offset.md +++ b/buffer/buf_writebiguint64le_value_offset.md @@ -6,7 +6,7 @@ added: v12.0.0 * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的字节序格式(`writeBigUInt64BE()` 写入大端序,`writeBigUInt64LE()` 写入小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +用指定的[字节序][endianness](`writeBigUInt64BE()` 写入为大端序,`writeBigUInt64LE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 ```js diff --git a/buffer/buf_writedoublele_value_offset.md b/buffer/buf_writedoublele_value_offset.md index 1251d38d..90b94655 100644 --- a/buffer/buf_writedoublele_value_offset.md +++ b/buffer/buf_writedoublele_value_offset.md @@ -11,9 +11,9 @@ changes: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的字节序格式(`writeDoubleBE()` 写入大端序,`writeDoubleLE()` 写入小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 -`value` 必须是 64 位双精度值。 -当 `value` 不是 64 位双精度值时,行为是未定义的。 +用指定的[字节序][endianness](`writeDoubleBE()` 写入为大端序,`writeDoubleLE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +`value` 必须是 JavaScript 数值。 +当 `value` 不是 JavaScript 数值时,行为是未定义的。 ```js const buf = Buffer.allocUnsafe(8); diff --git a/buffer/buf_writefloatle_value_offset.md b/buffer/buf_writefloatle_value_offset.md index ed10c8eb..f1d96a9f 100644 --- a/buffer/buf_writefloatle_value_offset.md +++ b/buffer/buf_writefloatle_value_offset.md @@ -12,9 +12,9 @@ changes: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的字节序格式(`writeFloatBE()` 写入大端序,`writeFloatLE()` 写入小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 -`value` 必须是 32 位浮点值。 -当 `value` 不是 32 位浮点值时,行为是未定义的。 +用指定的[字节序][endianness](`writeFloatBE()` 写入为大端序,`writeFloatLE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +`value` 必须是 JavaScript 数值。 +当 `value` 不是 JavaScript 数值时,行为是未定义的。 ```js const buf = Buffer.allocUnsafe(4); diff --git a/buffer/buf_writeint16le_value_offset.md b/buffer/buf_writeint16le_value_offset.md index 8c7f3a27..c9cf30b5 100644 --- a/buffer/buf_writeint16le_value_offset.md +++ b/buffer/buf_writeint16le_value_offset.md @@ -11,7 +11,7 @@ changes: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 2`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的字节序格式(`writeInt16BE()` 写入大端序,`writeInt16LE()` 写入小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +用指定的[字节序][endianness](`writeInt16BE()` 写入为大端序,`writeInt16LE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 `value` 必须是有符号的 16 位整数。 当 `value` 不是有符号的 16 位整数时,行为是未定义的。 diff --git a/buffer/buf_writeint32le_value_offset.md b/buffer/buf_writeint32le_value_offset.md index 8434bfc1..e36cddc3 100644 --- a/buffer/buf_writeint32le_value_offset.md +++ b/buffer/buf_writeint32le_value_offset.md @@ -11,7 +11,7 @@ changes: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的字节序格式(`writeInt32BE()` 写入大端序,`writeInt32LE()` 写入小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +用指定的[字节序][endianness](`writeInt32BE()` 写入为大端序,`writeInt32LE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 `value` 必须是有符号的 32 位整数。 当 `value` 不是有符号的 32 位整数,行为是未定义的。 diff --git a/buffer/buf_writeuint16le_value_offset.md b/buffer/buf_writeuint16le_value_offset.md index 5441cf85..4fc41bf0 100644 --- a/buffer/buf_writeuint16le_value_offset.md +++ b/buffer/buf_writeuint16le_value_offset.md @@ -11,7 +11,7 @@ changes: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 2`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的字节序格式(`writeUInt16BE()` 写入大端序,`writeUInt16LE()` 写入小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +用指定的[字节序][endianness](`writeUInt16BE()` 写入为大端序,`writeUInt16LE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 `value` 必须是无符号的 16 位整数。 当 `value` 不是无符号的 16 位整数时,行为是未定义的。 diff --git a/buffer/buf_writeuint32le_value_offset.md b/buffer/buf_writeuint32le_value_offset.md index 413716ea..4ceb3a40 100644 --- a/buffer/buf_writeuint32le_value_offset.md +++ b/buffer/buf_writeuint32le_value_offset.md @@ -11,7 +11,7 @@ changes: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的字节序格式(`writeUInt32BE()` 写入大端序,`writeUInt32LE()` 写入小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +用指定的[字节序][endianness](`writeUInt32BE()` 写入为大端序,`writeUInt32LE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 `value` 必须是无符号的 32 位整数。 当 `value` 不是无符号的 32 位整数时,行为是未定义的。 diff --git a/buffer/buffer.md b/buffer/buffer.md index 75a61c60..6f2bbb0a 100644 --- a/buffer/buffer.md +++ b/buffer/buffer.md @@ -3,18 +3,21 @@ > 稳定性: 2 - 稳定 -在引入 [`TypedArray`] 之前,JavaScript 语言没有用于读取或操作二进制数据流的机制。 -`Buffer` 类是作为 Node.js API 的一部分引入的,用于在 TCP 流、文件系统操作、以及其他上下文中与八位字节流进行交互。 +在 Node.js 中,`Buffer` 对象用于以字节序列的形式来表示二进制数据。 +许多 Node.js 的 API(例如流和文件系统操作)都支持 `Buffer`,因为与操作系统或其他进程的交互通常总是以二进制数据的形式发生。 -现在可以使用 [`TypedArray`],`Buffer` 类以更优化和更适合 Node.js 的方式实现了 [`Uint8Array`] API。 +`Buffer` 类是 JavaScript 语言内置的 [`Uint8Array`] 类的子类。 +支持许多涵盖其他用例的额外方法。 +只要支持 `Buffer` 的地方,Node.js API 都可以接受普通的 [`Uint8Array`]。 -`Buffer` 类的实例类似于从 `0` 到 `255` 之间的整数数组(其他整数会通过 `& 255` 操作强制转换到此范围),但对应于 V8 堆外部的固定大小的原始内存分配。 -`Buffer` 的大小在创建时确定,且无法更改。 +`Buffer` 类的实例,以及通常的 [`Uint8Array`],类似于从 `0` 到 `255` 之间的整数数组,但对应于固定大小的内存块,并且不能包含任何其他值。 +一个 `Buffer` 的大小在创建时确定,且无法更改。 `Buffer` 类在全局作用域中,因此无需使用 `require('buffer').Buffer`。 ```js -// 创建一个长度为 10、且用零填充的 Buffer。 +// 创建一个长度为 10 的 Buffer, +// 其中填充了全部值为 `1` 的字节。 const buf1 = Buffer.alloc(10); // 创建一个长度为 10、且用 0x1 填充的 Buffer。 @@ -23,16 +26,22 @@ const buf2 = Buffer.alloc(10, 1); // 创建一个长度为 10、且未初始化的 Buffer。 // 这个方法比调用 Buffer.alloc() 更快, // 但返回的 Buffer 实例可能包含旧数据, -// 因此需要使用 fill() 或 write() 重写。 +// 因此需要使用 fill()、write() 或其他能填充 Buffer 的内容的函数进行重写。 const buf3 = Buffer.allocUnsafe(10); -// 创建一个包含 [0x1, 0x2, 0x3] 的 Buffer。 +// 创建一个包含字节 [1, 2, 3] 的 Buffer。 const buf4 = Buffer.from([1, 2, 3]); -// 创建一个包含 UTF-8 字节 [0x74, 0xc3, 0xa9, 0x73, 0x74] 的 Buffer。 -const buf5 = Buffer.from('tést'); +// 创建一个包含字节 [1, 1, 1, 1] 的 Buffer, +// 其中所有条目均使用 `(value & 255)` 进行截断以符合 0-255 的范围。 +const buf5 = Buffer.from([257, 257.5, -255, '1']); + +// 创建一个 Buffer,其中包含字符串 'tést' 的 UTF-8 编码字节: +// [0x74, 0xc3, 0xa9, 0x73, 0x74](以十六进制表示) +// [116, 195, 169, 115, 116](以十进制表示) +const buf6 = Buffer.from('tést'); // 创建一个包含 Latin-1 字节 [0x74, 0xe9, 0x73, 0x74] 的 Buffer。 -const buf6 = Buffer.from('tést', 'latin1'); +const buf7 = Buffer.from('tést', 'latin1'); ``` diff --git a/buffer/buffer_constants_max_length.md b/buffer/buffer_constants_max_length.md index a48f5ea3..ab1a349c 100644 --- a/buffer/buffer_constants_max_length.md +++ b/buffer/buffer_constants_max_length.md @@ -4,8 +4,8 @@ added: v8.2.0 * {integer} 单个 `Buffer` 实例允许的最大内存。 -在 32 位的架构上,该值是 `(2^30)-1` (~1GB)。 -在 64 位的架构上,该值是 `(2^31)-1` (~2GB)。 +在 32 位的架构上,该值当前是 `(2^30)-1` (~1GB)。 +在 64 位的架构上,该值当前是 `(2^31)-1` (~2GB)。 也可使用 [`buffer.kMaxLength`]。 diff --git a/buffer/buffer_from_buffer_alloc_and_buffer_allocunsafe.md b/buffer/buffer_from_buffer_alloc_and_buffer_allocunsafe.md index d1134fa9..8a061dd4 100644 --- a/buffer/buffer_from_buffer_alloc_and_buffer_allocunsafe.md +++ b/buffer/buffer_from_buffer_alloc_and_buffer_allocunsafe.md @@ -3,7 +3,7 @@ * 将数字作为第一个参数传给 `Buffer()`(例如 `new Buffer(10)`)会分配一个指定大小的新建的 `Buffer` 对象。 在 Node.js 8.0.0 之前,为此类 `Buffer` 实例分配的内存是未初始化的,并且可能包含敏感数据。 - 此类 `Buffer` 实例随后必须被初始化,可以使用 [`buf.fill(0)`][`buf.fill()`] 或写满整个 `Buffer`。 + 此类 `Buffer` 实例随后必须被初始化,在从 `Buffer` 读取数据之前,可以使用 [`buf.fill(0)`][`buf.fill()`] 或写满整个 `Buffer`。 虽然这种行为是为了提高性能,但开发经验表明,创建一个快速但未初始化的 `Buffer` 与创建一个速度更慢但更安全的 `Buffer` 之间需要有更明确的区分。 从 Node.js 8.0.0 开始,`Buffer(num)` 和 `new Buffer(num)` 将返回已初始化内存的 `Buffer`。 * 传入字符串、数组、或 `Buffer` 作为第一个参数,则会将传入的对象的数据拷贝到 `Buffer` 中。 @@ -11,9 +11,9 @@ 由于 `new Buffer()` 的行为因第一个参数的类型而异,因此当未执行参数验证或 `Buffer` 初始化时,可能会无意中将安全性和可靠性问题引入应用程序。 -例如,如果攻击者可以使应用程序接收到数字(实际期望的是字符串),则应用程序可能调用 `new Buffer(100)` 而不是 `new Buffer("100")`,它将分配一个 100 个字节的 buffer 而不是分配一个内容为 `“100”` 的 3 个字节的 buffer。 +例如,如果攻击者可以使应用程序接收到数字(实际期望的是字符串),则应用程序可能调用 `new Buffer(100)` 而不是 `new Buffer("100")`,使其分配一个 100 个字节的 buffer 而不是分配一个内容为 `“100”` 的 3 个字节的 buffer。 使用 JSON API 调用时,是非常有可能发生这种情况的。 -由于 JSON 区分数字和字符串类型,因此它允许在简单的应用程序可能期望始终接收字符串的情况下注入数字。 +由于 JSON 区分数字和字符串类型,因此它允许在未充分验证其输入的简单写入的应用程序可能期望始终接收字符串的情况下注入数字。 在 Node.js 8.0.0 之前,100 个字节的 buffer 可能包含任意预先存在的内存数据,因此可能会用于向远程攻击者暴露内存中的机密。 从 Node.js 8.0.0 开始,由于数据会用零填充,因此不会发生内存暴露。 但是,其他攻击仍然存在,例如导致服务器分配非常大的 buffer,导致性能下降或内存耗尽崩溃。 @@ -32,7 +32,7 @@ * [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] 和 [`Buffer.allocUnsafeSlow(size)`][`Buffer.allocUnsafeSlow()`] 分别返回一个指定大小的新建的未初始化的 `Buffer`。 由于 `Buffer` 是未初始化的,因此分配的内存片段可能包含敏感的旧数据。 -如果 `size` 小于或等于 [`Buffer.poolSize`] 的一半,则 [`Buffer.allocUnsafe()`] 返回的 `Buffer` 实例可能是从共享的内部内存池中分配。 +如果 `size` 小于或等于 [`Buffer.poolSize`] 的一半,则 [`Buffer.allocUnsafe()`] 和 [`Buffer.from(array)`] 返回的 `Buffer` 实例可能是从共享的内部内存池中分配。 [`Buffer.allocUnsafeSlow()`] 返回的实例则从不使用共享的内部内存池。 diff --git a/buffer/buffers_and_character_encodings.md b/buffer/buffers_and_character_encodings.md index 55b963e8..81c80221 100644 --- a/buffer/buffers_and_character_encodings.md +++ b/buffer/buffers_and_character_encodings.md @@ -8,39 +8,67 @@ changes: description: Removed the deprecated `raw` and `raws` encodings. --> -当字符串数据被存储入 `Buffer` 实例或从 `Buffer` 实例中被提取时,可以指定一个字符编码。 +当在 `Buffer` 和字符串之间转换时,可以指定字符编码。 +如果未指定字符编码,则使用 UTF-8 作为默认值。 ```js -const buf = Buffer.from('hello world', 'ascii'); +const buf = Buffer.from('hello world', 'utf8'); console.log(buf.toString('hex')); // 打印: 68656c6c6f20776f726c64 console.log(buf.toString('base64')); // 打印: aGVsbG8gd29ybGQ= -console.log(Buffer.from('fhqwhgads', 'ascii')); +console.log(Buffer.from('fhqwhgads', 'utf8')); // 打印: console.log(Buffer.from('fhqwhgads', 'utf16le')); // 打印: ``` -Node.js 当前支持的字符编码有: +Node.js 当前支持的字符编码如下: -* `'ascii'`: 仅适用于 7 位 ASCII 数据。此编码速度很快,如果设置则会剥离高位。 +* `'utf8'`: 多字节编码的 Unicode 字符。 + 许多网页和其他文档格式都使用 UTF-8。 + 这是默认的字符编码。 + 当将 `Buffer` 解码为不专门包含有效 UTF-8 数据的字符串时,则会使用 Unicode 替换字符 `U+FFFD` � 来表示这些错误。 -* `'utf8'`: 多字节编码的 Unicode 字符。许多网页和其他文档格式都使用 UTF-8。 +* `'utf16le'`: 多字节编码的 Unicode 字符。 + 与 `'utf8'` 不同,字符串中的每个字符都会使用 2 个或 4 个字节进行编码。 + Node.js 仅支持 [UTF-16] 的[小端序][endianness]变体。 -* `'utf16le'`: 2 或 4 个字节,小端序编码的 Unicode 字符。支持代理对(U+10000 至 U+10FFFF)。 +* `'latin1'`: Latin-1 代表 [ISO-8859-1]。 + 此字符编码仅支持从 `U+0000` 到 `U+00FF` 的 Unicode 字符。 + 每个字符使用单个字节进行编码。 + 超出该范围的字符会被截断,并映射成该范围内的字符。 -* `'ucs2'`: `'utf16le'` 的别名。 +使用以上方法之一将 `Buffer` 转换为字符串,称为解码;将字符串转换为 `Buffer`,称为编码。 + +Node.js 还支持以下两种二进制转文本的编码。 +对于二进制转文本的编码,其命名约定是相反的:将 `Buffer` 转换为字符串通常称为编码,而将字符串转换为 `Buffer` 则称为解码。 -* `'base64'`: Base64 编码。当从字符串创建 `Buffer` 时,此编码也会正确地接受 [RFC 4648 第 5 节][RFC 4648, Section 5]中指定的 “URL 和文件名安全字母”。 +* `'base64'`: [Base64] 编码。 + 当从字符串创建 `Buffer` 时,此编码也会正确地接受 [RFC 4648 第 5 节][RFC 4648, Section 5]中指定的 “URL 和文件名安全字母”。 + +* `'hex'`: 将每个字节编码成两个十六进制的字符。 + 当解码仅包含有效的十六进制字符的字符串时,可能会发生数据截断。 + 请参阅下面的示例。 -* `'latin1'`: 一种将 `Buffer` 编码成单字节编码字符串的方法(由 [RFC 1345] 中的 IANA 定义,第 63 页,作为 Latin-1 的补充块和 C0/C1 控制码)。 +还支持以下遗留的字符编码: + +* `'ascii'`: 仅适用于 7 位 [ASCII] 数据。 + 当将字符串编码为 `Buffer` 时,这等效于使用 `'latin1'`。 + 当将 `Buffer` 解码为字符串时,则使用编码会在解码为 `'latin1'` 之前额外取消设置每个字节的最高位。 + 通常,当在编码或解码纯 ASCII 文本时,应该没有理由使用这种编码,因为 `'utf8'`(或者,如果已知的数据始终为纯 ASCII,则为 `'latin1'`)会是更好的选择。 + 这仅为遗留的兼容性而提供。 * `'binary'`: `'latin1'` 的别名。 + 有关此编码的更多背景,请参月[二进制字符串][binary strings]。 + 该编码的名称可能会引起误解,因为此处列出的所有编码都是在字符串和二进制数据之间转换。 + 对于在字符串和 `Buffer` 之间进行转换,通常 `'utf-8'` 是正确的选择。 -* `'hex'`: 将每个字节编码成两个十六进制的字符。 +* `'ucs2'`: `'utf16le'` 的别名。 + UCS-2 以前是指 UTF-16 的一种变体,该变体不支持代码点大于 U+FFFF 的字符。 + 在 Node.js 中,始终支持这些代码点。 ```js Buffer.from('1ag', 'hex'); diff --git a/buffer/buffers_and_typedarray.md b/buffer/buffers_and_typedarray.md deleted file mode 100644 index 39f4b5e1..00000000 --- a/buffer/buffers_and_typedarray.md +++ /dev/null @@ -1,65 +0,0 @@ - - -`Buffer` 实例也是 [`Uint8Array`] 实例,但是与 [`TypedArray`] 有微小的不同。 -例如,[`ArrayBuffer#slice()`] 会创建切片的拷贝,而 [`Buffer#slice()`][`buf.slice()`] 是在现有的 `Buffer` 上创建而不拷贝,这使得 [`Buffer#slice()`][`buf.slice()`] 效率更高。 - -也可以从一个 `Buffer` 创建新的 [`TypedArray`] 实例,但需要注意以下事项: - -1. `Buffer` 对象的内存是被拷贝到 [`TypedArray`],而不是共享。 - -2. `Buffer` 对象的内存是被解释为不同元素的数组,而不是目标类型的字节数组。 -也就是说,`new Uint32Array(Buffer.from([1, 2, 3, 4]))` 会创建一个带有 4 个元素 `[1, 2, 3, 4]` 的 [`Uint32Array`],而不是带有单个元素 `[0x1020304]` 或 `[0x4030201]` 的 [`Uint32Array`]。 - -通过使用 `TypedArray` 对象的 `.buffer` 属性,可以创建一个与 [`TypedArray`] 实例共享相同内存的新 `Buffer`。 - -```js -const arr = new Uint16Array(2); - -arr[0] = 5000; -arr[1] = 4000; - -// 拷贝 `arr` 的内容。 -const buf1 = Buffer.from(arr); -// 与 `arr` 共享内存。 -const buf2 = Buffer.from(arr.buffer); - -console.log(buf1); -// 打印: -console.log(buf2); -// 打印: - -arr[1] = 6000; - -console.log(buf1); -// 打印: -console.log(buf2); -// 打印: -``` - -当使用 [`TypedArray`] 的 `.buffer` 创建 `Buffer` 时,也可以通过传入 `byteOffset` 和 `length` 参数只使用 [`TypedArray`] 的一部分。 - -```js -const arr = new Uint16Array(20); -const buf = Buffer.from(arr.buffer, 0, 16); - -console.log(buf.length); -// 打印: 16 -``` - -`Buffer.from()` 与 [`TypedArray.from()`] 有着不同的实现。 -具体来说,[`TypedArray`] 可以接受第二个参数作为映射函数,在类型数组的每个元素上调用: - -* `TypedArray.from(source[, mapFn[, thisArg]])` - -`Buffer.from()` 则不支持映射函数的使用: - -* [`Buffer.from(array)`] -* [`Buffer.from(buffer)`] -* [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`] -* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] - diff --git a/buffer/buffers_and_typedarrays.md b/buffer/buffers_and_typedarrays.md new file mode 100644 index 00000000..d73f3ce1 --- /dev/null +++ b/buffer/buffers_and_typedarrays.md @@ -0,0 +1,83 @@ + + +`Buffer` 实例也是 [`Uint8Array`] 实例,这是该语言用于处理二进制数据的内置类。 +[`Uint8Array`] 依次是 [`TypedArray`] 的子类。 +因此,所有 [`TypedArray`] 的方法在 `Buffer` 上也可用。 +但是,`Buffer` 的 API 和 [`TypedArray`] 的 API 之间存在细微的不兼容。 + +主要表现在: + +* [`TypedArray#slice()`] 会创建 `TypedArray` 的片段的拷贝,而 [`Buffer#slice()`][`buf.slice()`] 是在现有的 `Buffer` 上创建视图而不进行拷贝。 + 此行为可能产生意外,并且仅用于旧版的兼容性。 + [`TypedArray#subarray()`] 可用于在 `Buffer` 和其他 `TypedArray` 上实现 [`Buffer#slice()`][`buf.slice()`] 的行为。 +* [`buf.toString()`] 与它在 `TypedArray` 上的等价物并不兼容。 +* 一些方法,例如 [`buf.indexOf()`],支持额外的参数。 + +有两种方法可以从一个 `Buffer` 创建新的 [`TypedArray`] 实例。 + +当将一个 `Buffer` 传给 [`TypedArray`] 的构造函数时,该 `Buffer` 的元素会被拷贝且,且会被解析为一个整数数组,而不是目标类型的字节数组。 +例如,`new Uint32Array(Buffer.from([1, 2, 3, 4]))` 会创建一个带有 4 个元素 `[1, 2, 3, 4]` 的 [`Uint32Array`],而不是带有单个元素 `[0x1020304]` 或 `[0x4030201]` 的 [`Uint32Array`]。 + + +为了创建与 `Buffer` 共享其内存的 [`TypedArray`],可以将底层的 [`ArrayBuffer`] 传给 [`TypedArray`] 的构造函数: + +```js +const buf = Buffer.from('hello', 'utf16le'); +const uint16arr = new Uint16Array( + buf.buffer, buf.byteOffset, buf.length / Uint16Array.BYTES_PER_ELEMENT); +``` + +也可以通过使用 `TypedArray` 对象的 `.buffer` 属性,以相同的方式来创建一个与 [`TypedArray`] 实例共享相同分配内存的新 `Buffer`。 +在这种情况下,[`Buffer.from()`][`Buffer.from(arrayBuf)`] 的行为类似于 `new Uint8Array()`。 + +```js +const arr = new Uint16Array(2); + +arr[0] = 5000; +arr[1] = 4000; + +// 拷贝 `arr` 的内容。 +const buf1 = Buffer.from(arr); +// 与 `arr` 共享内存。 +const buf2 = Buffer.from(arr.buffer); + +console.log(buf1); +// 打印: +console.log(buf2); +// 打印: + +arr[1] = 6000; + +console.log(buf1); +// 打印: +console.log(buf2); +// 打印: +``` + +当使用 [`TypedArray`] 的 `.buffer` 创建 `Buffer` 时,也可以通过传入 `byteOffset` 和 `length` 参数只使用底层 [`ArrayBuffer`] 的一部分。 + +```js +const arr = new Uint16Array(20); +const buf = Buffer.from(arr.buffer, 0, 16); + +console.log(buf.length); +// 打印: 16 +``` + +`Buffer.from()` 与 [`TypedArray.from()`] 有着不同的实现。 +具体来说,[`TypedArray`] 可以接受第二个参数作为映射函数,在类型数组的每个元素上调用: + +* `TypedArray.from(source[, mapFn[, thisArg]])` + +`Buffer.from()` 方法则不支持映射函数的使用: + +* [`Buffer.from(array)`][] +* [`Buffer.from(buffer)`][] +* [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`] +* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] + diff --git a/buffer/class_method_buffer_alloc_size_fill_encoding.md b/buffer/class_method_buffer_alloc_size_fill_encoding.md index 6b4a56a0..8310304d 100644 --- a/buffer/class_method_buffer_alloc_size_fill_encoding.md +++ b/buffer/class_method_buffer_alloc_size_fill_encoding.md @@ -30,7 +30,6 @@ console.log(buf); ``` 如果 `size` 大于 [`buffer.constants.MAX_LENGTH`] 或小于 0,则抛出 [`ERR_INVALID_OPT_VALUE`]。 -如果 `size` 为 0,则创建一个零长度的 `Buffer`。 如果指定了 `fill`,则分配的 `Buffer` 通过调用 [`buf.fill(fill)`][`buf.fill()`] 进行初始化。 @@ -50,7 +49,7 @@ console.log(buf); // 打印: ``` -调用 [`Buffer.alloc()`] 可能比替代的 [`Buffer.allocUnsafe()`] 慢得多,但能确保新创建的 `Buffer` 实例的内容永远不会包含敏感的数据。 +调用 [`Buffer.alloc()`] 可能比替代的 [`Buffer.allocUnsafe()`] 慢得多,但能确保新创建的 `Buffer` 实例的内容永远不会包含来自先前分配的敏感数据,包括可能尚未分配给 `Buffer` 的数据。 如果 `size` 不是一个数字,则抛出 `TypeError`。 diff --git a/buffer/class_method_buffer_allocunsafe_size.md b/buffer/class_method_buffer_allocunsafe_size.md index 5484b2a4..2a8cb582 100644 --- a/buffer/class_method_buffer_allocunsafe_size.md +++ b/buffer/class_method_buffer_allocunsafe_size.md @@ -10,7 +10,6 @@ changes: 创建一个大小为 `size` 字节的新 `Buffer`。 如果 `size` 大于 [`buffer.constants.MAX_LENGTH`] 或小于 0,则抛出 [`ERR_INVALID_OPT_VALUE`]。 -如果 `size` 为 0,则创建一个长度为零的 `Buffer`。 以这种方式创建的 `Buffer` 实例的底层内存是未初始化的。 新创建的 `Buffer` 的内容是未知的,可能包含敏感数据。 @@ -30,7 +29,7 @@ console.log(buf); 如果 `size` 不是一个数字,则抛出 `TypeError`。 -`Buffer` 模块会预分配一个内部的大小为 [`Buffer.poolSize`] 的 `Buffer` 实例,作为快速分配的内存池,用于使用 [`Buffer.allocUnsafe()`] 创建新的 `Buffer` 实例、或废弃的 `new Buffer(size)` 构造器但仅当 `size` 小于或等于 `Buffer.poolSize >> 1`([`Buffer.poolSize`] 除以二再向下取整)。 +`Buffer` 模块会预分配一个内部的大小为 [`Buffer.poolSize`] 的 `Buffer` 实例,作为快速分配的内存池,用于使用 [`Buffer.allocUnsafe()`] 创建新的 `Buffer` 实例、或 [`Buffer.from(array)`]、或废弃的 `new Buffer(size)` 构造器但仅当 `size` 小于或等于 `Buffer.poolSize >> 1`([`Buffer.poolSize`] 除以二再向下取整)。 对这个预分配的内部内存池的使用是调用 `Buffer.alloc(size, fill)` 和 `Buffer.allocUnsafe(size).fill(fill)` 两者之间的关键区别。 具体来说,`Buffer.alloc(size, fill)` 永远不会使用内部的 `Buffer` 池,而 `Buffer.allocUnsafe(size).fill(fill)` 在 `size` 小于或等于 [`Buffer.poolSize`] 的一半时将会使用内部的 `Buffer`池。 diff --git a/buffer/class_method_buffer_allocunsafeslow_size.md b/buffer/class_method_buffer_allocunsafeslow_size.md index 93ef0e07..7b37791e 100644 --- a/buffer/class_method_buffer_allocunsafeslow_size.md +++ b/buffer/class_method_buffer_allocunsafeslow_size.md @@ -14,7 +14,7 @@ added: v5.12.0 当使用 [`Buffer.allocUnsafe()`] 创建新的 `Buffer` 实例时,如果要分配的内存小于 4KB,则会从一个预分配的 `Buffer` 切割出来。 这可以避免垃圾回收机制因创建太多独立的 `Buffer` 而过度使用。 -这种方式通过消除跟踪和清理的需要来改进性能和内存使用。 +通过消除跟踪和清理尽可能多的单个 `ArrayBuffer` 对象的需要,该方法可以提高性能和内存使用率。 当开发人员需要在内存池中保留一小块内存时,可以使用 `Buffer.allocUnsafeSlow()` 创建一个非内存池的 `Buffer` 实例并拷贝相关的比特位出来。 @@ -36,6 +36,4 @@ socket.on('readable', () => { }); ``` -`Buffer.allocUnsafeSlow()` 应该只用作开发人员已经在其应用程序中观察到过度的内存之后的最后手段。 - 如果 `size` 不是一个数字,则抛出 `TypeError`。 diff --git a/buffer/class_method_buffer_bytelength_string_encoding.md b/buffer/class_method_buffer_bytelength_string_encoding.md index a5982fd2..c4631496 100644 --- a/buffer/class_method_buffer_bytelength_string_encoding.md +++ b/buffer/class_method_buffer_bytelength_string_encoding.md @@ -14,11 +14,11 @@ changes: * `encoding` {string} 如果 `string` 是字符串,则这是它的字符编码。**默认值:** `'utf8'`。 * 返回: {integer} `string` 中包含的字节数。 -返回字符串的实际字节长度。 -与 [`String.prototype.length`] 不同,后者返回字符串的字符数。 +当使用 `encoding` 进行编码时,返回字符串的字节长度。 +与 [`String.prototype.length`] 不同,后者不会考虑用于将字符串转换为字节的编码。 对于 `'base64'` 和 `'hex'`,此函数会假定输入是有效的。 -对于包含非 Base64/Hex 编码的数据(例如空格)的字符串,返回值可能是大于从字符串创建的 `Buffer` 的长度。 +对于包含非 base64/hex 编码的数据(例如空格)的字符串,返回值可能是大于从字符串创建的 `Buffer` 的长度。 ```js const str = '\u00bd + \u00bc = \u00be'; @@ -28,5 +28,5 @@ console.log(`${str}: ${str.length} 个字符, ` + // 打印: ½ + ¼ = ¾: 9 个字符, 12 个字节 ``` -当 `string` 是一个 `Buffer`/[`DataView`][]/[`TypedArray`][]/[`ArrayBuffer`][]/[`SharedArrayBuffer`] 时,返回实际的字节长度。 +当 `string` 是一个 `Buffer`/[`DataView`][]/[`TypedArray`][]/[`ArrayBuffer`][]/[`SharedArrayBuffer`] 时,返回 `.byteLength` 报告的字节长度。 diff --git a/buffer/class_method_buffer_compare_buf1_buf2.md b/buffer/class_method_buffer_compare_buf1_buf2.md index 7bce2a27..6aa2329d 100644 --- a/buffer/class_method_buffer_compare_buf1_buf2.md +++ b/buffer/class_method_buffer_compare_buf1_buf2.md @@ -8,7 +8,7 @@ changes: * `buf1` {Buffer|Uint8Array} * `buf2` {Buffer|Uint8Array} -* 返回: {integer} +* 返回: {integer} `-1`、`0` 或 `1`,取决于比较的结果。 有关详细信息,参阅 [`buf.compare()`]。 比较 `buf1` 与 `buf2`,主要用于 `Buffer` 实例数组的排序。 相当于调用 [`buf1.compare(buf2)`][`buf.compare()`]。 diff --git a/buffer/class_method_buffer_concat_list_totallength.md b/buffer/class_method_buffer_concat_list_totallength.md index 3da852c4..49a0b833 100644 --- a/buffer/class_method_buffer_concat_list_totallength.md +++ b/buffer/class_method_buffer_concat_list_totallength.md @@ -14,8 +14,7 @@ changes: 如果 `list` 中没有元素、或 `totalLength` 为 0,则返回一个长度为 0 的 `Buffer`。 -如果没有提供 `totalLength`,则计算 `list` 中的 `Buffer` 实例的总长度。 -但是这会导致执行额外的循环用于计算 `totalLength`,因此如果已知长度,则明确提供长度会更快。 +如果没有提供 `totalLength`,则通过将 `list` 中的 `Buffer` 实例的长度相加来计算得出。 如果提供了 `totalLength`,则会强制转换为无符号整数。 如果 `list` 中的 `Buffer` 合并后的总长度大于 `totalLength`,则结果会被截断到 `totalLength` 的长度。 diff --git a/buffer/class_method_buffer_from_array.md b/buffer/class_method_buffer_from_array.md index e0d17031..78a6dd8f 100644 --- a/buffer/class_method_buffer_from_array.md +++ b/buffer/class_method_buffer_from_array.md @@ -4,7 +4,8 @@ added: v5.10.0 * `array` {integer[]} -使用八位字节数组 `array` 分配一个新的 `Buffer`。 +使用 `0` – `255` 范围内的字节数组 `array` 来分配一个新的 `Buffer`。 +超出该范围的数组条目会被截断以适合它。 ```js // 创建一个包含字符串 'buffer' 的 UTF-8 字节的新 Buffer。 @@ -13,3 +14,5 @@ const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); 如果 `array` 不是一个 `Array` 或适用于 `Buffer.from()` 变量的其他类型,则抛出 `TypeError`。 +`Buffer.from(array)` 和 [`Buffer.from(string)`] 也可以像 [`Buffer.allocUnsafe()`] 一样使用内部的 `Buffer` 池。 + diff --git a/buffer/class_method_buffer_from_arraybuffer_byteoffset_length.md b/buffer/class_method_buffer_from_arraybuffer_byteoffset_length.md index 3cf11e5c..3c633383 100644 --- a/buffer/class_method_buffer_from_arraybuffer_byteoffset_length.md +++ b/buffer/class_method_buffer_from_arraybuffer_byteoffset_length.md @@ -2,7 +2,7 @@ added: v5.10.0 --> -* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} 一个 [`ArrayBuffer`]、[`SharedArrayBuffer`]、或 [`TypedArray`] 的 `.buffer` 属性。 +* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} 一个 [`ArrayBuffer`] 或 [`SharedArrayBuffer`],例如 [`TypedArray`] 的 `.buffer` 属性。 * `byteOffset` {integer} 开始拷贝的索引。**默认值:** `0`。 * `length` {integer} 拷贝的字节数。**默认值:** `arrayBuffer.byteLength - byteOffset`。 diff --git a/buffer/class_method_buffer_from_string_encoding.md b/buffer/class_method_buffer_from_string_encoding.md index 4b964f1b..6e89a0a5 100644 --- a/buffer/class_method_buffer_from_string_encoding.md +++ b/buffer/class_method_buffer_from_string_encoding.md @@ -6,7 +6,7 @@ added: v5.10.0 * `encoding` {string} `string` 的字符编码。**默认值:** `'utf8'`。 创建一个包含 `string` 的新 `Buffer`。 -`encoding` 参数指定 `string` 的字符编码。 +`encoding` 参数指定用于将 `string` 转换为字节的字符编码。 ```js const buf1 = Buffer.from('this is a tést'); @@ -16,8 +16,8 @@ console.log(buf1.toString()); // 打印: this is a tést console.log(buf2.toString()); // 打印: this is a tést -console.log(buf1.toString('ascii')); -// 打印: this is a tC)st +console.log(buf1.toString('latin1')); +// 打印: this is a tést ``` 如果 `string` 不是一个字符串或适用于 `Buffer.from()` 变量的其他类型,则抛出 `TypeError`。 diff --git a/buffer/class_method_buffer_isencoding_encoding.md b/buffer/class_method_buffer_isencoding_encoding.md index 458022f1..b15d7e8e 100644 --- a/buffer/class_method_buffer_isencoding_encoding.md +++ b/buffer/class_method_buffer_isencoding_encoding.md @@ -5,7 +5,7 @@ added: v0.9.1 * `encoding` {string} 要检查的字符编码名称。 * 返回: {boolean} -如果 `encoding` 是支持的字符编码,则返回 `true`,否则返回 `false`。 +如果 `encoding` 是支持的字符编码的名称,则返回 `true`,否则返回 `false`。 ```js console.log(Buffer.isEncoding('utf-8')); diff --git a/buffer/class_slowbuffer.md b/buffer/class_slowbuffer.md index 00106ea4..94ec3b1f 100644 --- a/buffer/class_slowbuffer.md +++ b/buffer/class_slowbuffer.md @@ -4,34 +4,7 @@ deprecated: v6.0.0 > Stability: 0 - Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead. -Returns an un-pooled `Buffer`. - -In order to avoid the garbage collection overhead of creating many individually -allocated `Buffer` instances, by default allocations under 4KB are sliced from a -single larger allocated object. - -In the case where a developer may need to retain a small chunk of memory from a -pool for an indeterminate amount of time, it may be appropriate to create an -un-pooled `Buffer` instance using `SlowBuffer` then copy out the relevant bits. - -```js -// Need to keep around a few small chunks of memory. -const store = []; - -socket.on('readable', () => { - let data; - while (null !== (data = readable.read())) { - // Allocate for retained data. - const sb = SlowBuffer(10); - - // Copy the data into the new allocation. - data.copy(sb, 0, 0, 10); - - store.push(sb); - } -}); -``` - -Use of `SlowBuffer` should be used only as a last resort *after* a developer -has observed undue memory retention in their applications. +See [`Buffer.allocUnsafeSlow()`][]. This was never a class in the sense that +the constructor always returned a `Buffer` instance, rather than a `SlowBuffer` +instance. diff --git a/buffer/new_buffer_array.md b/buffer/new_buffer_array.md index aadcdc9b..f985a00e 100644 --- a/buffer/new_buffer_array.md +++ b/buffer/new_buffer_array.md @@ -17,10 +17,5 @@ changes: * `array` {integer[]} An array of bytes to copy from. -Allocates a new `Buffer` using an `array` of octets. - -```js -// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. -const buf = new Buffer([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); -``` +See [`Buffer.from(array)`][]. diff --git a/buffer/new_buffer_arraybuffer_byteoffset_length.md b/buffer/new_buffer_arraybuffer_byteoffset_length.md index 2e71b3ce..abcbab5b 100644 --- a/buffer/new_buffer_arraybuffer_byteoffset_length.md +++ b/buffer/new_buffer_arraybuffer_byteoffset_length.md @@ -27,30 +27,6 @@ changes: * `length` {integer} Number of bytes to expose. **Default:** `arrayBuffer.byteLength - byteOffset`. -This creates a view of the [`ArrayBuffer`][] or [`SharedArrayBuffer`][] without -copying the underlying memory. For example, when passed a reference to the -`.buffer` property of a [`TypedArray`][] instance, the newly created `Buffer` -will share the same allocated memory as the [`TypedArray`][]. - -The optional `byteOffset` and `length` arguments specify a memory range within -the `arrayBuffer` that will be shared by the `Buffer`. - -```js -const arr = new Uint16Array(2); - -arr[0] = 5000; -arr[1] = 4000; - -// Shares memory with `arr`. -const buf = new Buffer(arr.buffer); - -console.log(buf); -// Prints: - -// Changing the original Uint16Array changes the Buffer also. -arr[1] = 6000; - -console.log(buf); -// Prints: -``` +See +[`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]. diff --git a/buffer/new_buffer_buffer.md b/buffer/new_buffer_buffer.md index 9143a9b1..4f240022 100644 --- a/buffer/new_buffer_buffer.md +++ b/buffer/new_buffer_buffer.md @@ -18,17 +18,5 @@ changes: * `buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from which to copy data. -Copies the passed `buffer` data onto a new `Buffer` instance. - -```js -const buf1 = new Buffer('buffer'); -const buf2 = new Buffer(buf1); - -buf1[0] = 0x61; - -console.log(buf1.toString()); -// Prints: auffer -console.log(buf2.toString()); -// Prints: buffer -``` +See [`Buffer.from(buffer)`][]. diff --git a/buffer/new_buffer_size.md b/buffer/new_buffer_size.md index da07487f..8ea4392c 100644 --- a/buffer/new_buffer_size.md +++ b/buffer/new_buffer_size.md @@ -22,20 +22,8 @@ changes: * `size` {integer} The desired length of the new `Buffer`. -Allocates a new `Buffer` of `size` bytes. If `size` is larger than -[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][] -is thrown. A zero-length `Buffer` is created if `size` is 0. - -Prior to Node.js 8.0.0, the underlying memory for `Buffer` instances -created in this way is *not initialized*. The contents of a newly created -`Buffer` are unknown and *may contain sensitive data*. Use -[`Buffer.alloc(size)`][`Buffer.alloc()`] instead to initialize a `Buffer` -with zeroes. - -```js -const buf = new Buffer(10); - -console.log(buf); -// Prints: -``` +See [`Buffer.alloc()`][] and [`Buffer.allocUnsafe()`][]. This variant of the +constructor is equivalent to [`Buffer.allocUnsafe()`][], although using +[`Buffer.alloc()`][] is recommended in code paths that are not critical to +performance. diff --git a/buffer/new_buffer_string_encoding.md b/buffer/new_buffer_string_encoding.md index 05222389..fe0b3954 100644 --- a/buffer/new_buffer_string_encoding.md +++ b/buffer/new_buffer_string_encoding.md @@ -19,18 +19,5 @@ changes: * `string` {string} String to encode. * `encoding` {string} The encoding of `string`. **Default:** `'utf8'`. -Creates a new `Buffer` containing `string`. The `encoding` parameter identifies -the character encoding of `string`. - -```js -const buf1 = new Buffer('this is a tést'); -const buf2 = new Buffer('7468697320697320612074c3a97374', 'hex'); - -console.log(buf1.toString()); -// Prints: this is a tést -console.log(buf2.toString()); -// Prints: this is a tést -console.log(buf1.toString('ascii')); -// Prints: this is a tC)st -``` +See [`Buffer.from(string[, encoding])`][`Buffer.from(string)`]. diff --git a/buffer/new_slowbuffer_size.md b/buffer/new_slowbuffer_size.md index 0ae507c9..f855a3d3 100644 --- a/buffer/new_slowbuffer_size.md +++ b/buffer/new_slowbuffer_size.md @@ -6,26 +6,5 @@ deprecated: v6.0.0 * `size` {integer} The desired length of the new `SlowBuffer`. -Allocates a new `Buffer` of `size` bytes. If `size` is larger than -[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][] -is thrown. A zero-length `Buffer` is created if `size` is 0. - -The underlying memory for `SlowBuffer` instances is *not initialized*. The -contents of a newly created `SlowBuffer` are unknown and may contain sensitive -data. Use [`buf.fill(0)`][`buf.fill()`] to initialize a `SlowBuffer` with -zeroes. - -```js -const { SlowBuffer } = require('buffer'); - -const buf = new SlowBuffer(5); - -console.log(buf); -// Prints: (contents may vary): - -buf.fill(0); - -console.log(buf); -// Prints: -``` +See [`Buffer.allocUnsafeSlow()`][]. diff --git a/child_process/advanced_serialization.md b/child_process/advanced_serialization.md index 13e2091d..24699d35 100644 --- a/child_process/advanced_serialization.md +++ b/child_process/advanced_serialization.md @@ -1,5 +1,5 @@ Child processes support a serialization mechanism for IPC that is based on the diff --git a/child_process/child_process.md b/child_process/child_process.md index de6df678..6796a6cf 100644 --- a/child_process/child_process.md +++ b/child_process/child_process.md @@ -29,6 +29,10 @@ ls.on('close', (code) => { 这与 shell 中的管道的行为相同。 如果不消费输出,则使用 `{ stdio: 'ignore' }` 选项。 +如果传入 `options` 对象,则会使用 `options.env.PATH` 环境变量来执行命令查找,否则会使用 `process.env.PATH`。 +考虑到 Windows 的环境变量不区分大小写,Node.js 会按字典顺序对所有 `env` 键进行排序,并选择第一个不区分大小写的 `PATH` 来执行命令查找。 +当传给 `env` 选项的对象具有多个 `PATH` 变量时,在 Windows 上可能会出现问题。 + [`child_process.spawn()`] 方法异步地衍生子进程,且不阻塞 Node.js 事件循环。 [`child_process.spawnSync()`] 函数则以同步的方式提供了等效的功能,但会阻塞事件循环直到衍生的进程退出或终止。 diff --git a/child_process/child_process_fork_modulepath_args_options.md b/child_process/child_process_fork_modulepath_args_options.md index 40cbcf1a..0d3abf5c 100644 --- a/child_process/child_process_fork_modulepath_args_options.md +++ b/child_process/child_process_fork_modulepath_args_options.md @@ -1,7 +1,7 @@ * {Object} 一个管道,表示子进程的 IPC 通道。 diff --git a/child_process/subprocess_channel_ref.md b/child_process/subprocess_channel_ref.md new file mode 100644 index 00000000..41274604 --- /dev/null +++ b/child_process/subprocess_channel_ref.md @@ -0,0 +1,7 @@ + + +This method makes the IPC channel keep the event loop of the parent process +running if `.unref()` has been called before. + diff --git a/child_process/subprocess_channel_unref.md b/child_process/subprocess_channel_unref.md new file mode 100644 index 00000000..be0b6188 --- /dev/null +++ b/child_process/subprocess_channel_unref.md @@ -0,0 +1,7 @@ + + +This method makes the IPC channel not keep the event loop of the parent process +running, and lets it finish even while the channel is open. + diff --git a/cli/disable_proto_mode.md b/cli/disable_proto_mode.md new file mode 100644 index 00000000..213bf433 --- /dev/null +++ b/cli/disable_proto_mode.md @@ -0,0 +1,8 @@ + + +Disable the `Object.prototype.__proto__` property. If `mode` is `delete`, the +property will be removed entirely. If `mode` is `throw`, accesses to the +property will throw an exception with the code `ERR_PROTO_ACCESS`. + diff --git a/cli/experimental_import_meta_resolve.md b/cli/experimental_import_meta_resolve.md index 06a2ba9d..11ddbfb6 100644 --- a/cli/experimental_import_meta_resolve.md +++ b/cli/experimental_import_meta_resolve.md @@ -1,5 +1,5 @@ Enable experimental `import.meta.resolve()` support. diff --git a/cli/experimental_modules.md b/cli/experimental_modules.md index 91624463..1fe15727 100644 --- a/cli/experimental_modules.md +++ b/cli/experimental_modules.md @@ -2,5 +2,5 @@ added: v8.5.0 --> -Enable experimental ES module support and caching modules. +Enable latest experimental modules features (deprecated). diff --git a/cli/experimental_report.md b/cli/experimental_report.md deleted file mode 100644 index 95c8e88d..00000000 --- a/cli/experimental_report.md +++ /dev/null @@ -1,6 +0,0 @@ - - -Enable experimental diagnostic report feature. - diff --git a/cli/experimental_specifier_resolution_mode.md b/cli/experimental_specifier_resolution_mode.md index 2a4b4741..3cf10af0 100644 --- a/cli/experimental_specifier_resolution_mode.md +++ b/cli/experimental_specifier_resolution_mode.md @@ -1,5 +1,5 @@ Sets the resolution algorithm for resolving ES module specifiers. Valid options diff --git a/cli/experimental_wasi_unstable_preview1.md b/cli/experimental_wasi_unstable_preview1.md index 9f45b6e2..a8868349 100644 --- a/cli/experimental_wasi_unstable_preview1.md +++ b/cli/experimental_wasi_unstable_preview1.md @@ -1,5 +1,10 @@ Enable experimental WebAssembly System Interface (WASI) support. diff --git a/cli/http_parser_library.md b/cli/http_parser_library.md deleted file mode 100644 index 3013c951..00000000 --- a/cli/http_parser_library.md +++ /dev/null @@ -1,15 +0,0 @@ - - -Chooses an HTTP parser library. Available values are: - -* `llhttp` for https://llhttp.org/ -* `legacy` for https://github.com/nodejs/http-parser - -The default is `llhttp`, unless otherwise specified when building Node.js. - -This flag exists to aid in experimentation with the internal implementation of -the Node.js http parser. -This flag is likely to become a no-op and removed at some point in the future. - diff --git a/cli/http_server_default_timeout_milliseconds.md b/cli/http_server_default_timeout_milliseconds.md deleted file mode 100644 index 746d1c14..00000000 --- a/cli/http_server_default_timeout_milliseconds.md +++ /dev/null @@ -1,10 +0,0 @@ - - -Overrides the default value of `http`, `https` and `http2` server socket -timeout. Setting the value to 0 disables server socket timeout. Unless -provided, http server sockets timeout after 120s (2 minutes). Programmatic -setting of the timeout takes precedence over the value set through this -flag. - diff --git a/cli/input_type_type.md b/cli/input_type_type.md index f1a8a900..1b4d2f90 100644 --- a/cli/input_type_type.md +++ b/cli/input_type_type.md @@ -2,9 +2,8 @@ added: v12.0.0 --> -Used with `--experimental-modules`, this configures Node.js to interpret string -input as CommonJS or as an ES module. String input is input via `--eval`, -`--print`, or `STDIN`. +This configures Node.js to interpret string input as CommonJS or as an ES +module. String input is input via `--eval`, `--print`, or `STDIN`. Valid values are `"commonjs"` and `"module"`. The default is `"commonjs"`. diff --git a/cli/insecure_http_parser.md b/cli/insecure_http_parser.md index 814dacee..6f413c8a 100644 --- a/cli/insecure_http_parser.md +++ b/cli/insecure_http_parser.md @@ -1,5 +1,5 @@ Use an insecure HTTP parser that accepts invalid HTTP headers. This may allow diff --git a/cli/max_http_header_size_size.md b/cli/max_http_header_size_size.md index cfce79a2..4d999b18 100644 --- a/cli/max_http_header_size_size.md +++ b/cli/max_http_header_size_size.md @@ -1,6 +1,10 @@ -Specify the maximum size, in bytes, of HTTP headers. Defaults to 8KB. +Specify the maximum size, in bytes, of HTTP headers. Defaults to 16KB. diff --git a/cli/max_old_space_size_size_in_mbytes.md b/cli/max_old_space_size_size_in_mbytes.md new file mode 100644 index 00000000..3e74cf93 --- /dev/null +++ b/cli/max_old_space_size_size_in_mbytes.md @@ -0,0 +1,34 @@ + +Sets the max memory size of V8's old memory section. As memory +consumption approaches the limit, V8 will spend more time on +garbage collection in an effort to free unused memory. + +On a machine with 2GB of memory, consider setting this to +1536 (1.5GB) to leave some memory for other uses and avoid swapping. + +```console +$ node --max-old-space-size=1536 index.js +``` + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cli/node_options_options.md b/cli/node_options_options.md index 66c62e9a..c0f7e9ab 100644 --- a/cli/node_options_options.md +++ b/cli/node_options_options.md @@ -35,6 +35,7 @@ node --require "./a.js" --require "./b.js" Node.js options that are allowed are: +* `--disable-proto` * `--enable-fips` * `--enable-source-maps` * `--experimental-import-meta-resolve` @@ -43,7 +44,6 @@ Node.js options that are allowed are: * `--experimental-modules` * `--experimental-policy` * `--experimental-repl-await` -* `--experimental-report` * `--experimental-specifier-resolution` * `--experimental-vm-modules` * `--experimental-wasi-unstable-preview1` @@ -53,7 +53,6 @@ Node.js options that are allowed are: * `--frozen-intrinsics` * `--heapsnapshot-signal` * `--http-parser` -* `--http-server-default-timeout` * `--icu-data-dir` * `--input-type` * `--insecure-http-parser` @@ -73,6 +72,7 @@ Node.js options that are allowed are: * `--preserve-symlinks` * `--prof-process` * `--redirect-warnings` +* `--report-compact` * `--report-directory` * `--report-filename` * `--report-on-fatalerror` @@ -95,6 +95,7 @@ Node.js options that are allowed are: * `--trace-event-file-pattern` * `--trace-events-enabled` * `--trace-exit` +* `--trace-sigint` * `--trace-sync-io` * `--trace-tls` * `--trace-uncaught` @@ -102,6 +103,7 @@ Node.js options that are allowed are: * `--track-heap-objects` * `--unhandled-rejections` * `--use-bundled-ca` +* `--use-largepages` * `--use-openssl-ca` * `--v8-pool-size` * `--zero-fill-buffers` @@ -111,6 +113,7 @@ V8 options that are allowed are: * `--abort-on-uncaught-exception` * `--disallow-code-generation-from-strings` +* `--huge-max-old-generation-size` * `--interpreted-frames-native-stack` * `--jitless` * `--max-old-space-size` diff --git a/cli/node_repl_external_module_file.md b/cli/node_repl_external_module_file.md index 1cff0ce5..89f496dd 100644 --- a/cli/node_repl_external_module_file.md +++ b/cli/node_repl_external_module_file.md @@ -1,5 +1,5 @@ Path to a Node.js module which will be loaded in place of the built-in REPL. diff --git a/cli/report_compact.md b/cli/report_compact.md new file mode 100644 index 00000000..8af5c5e0 --- /dev/null +++ b/cli/report_compact.md @@ -0,0 +1,8 @@ + + +Write reports in a compact format, single-line JSON, more easily consumable +by log processing systems than the default multi-line format designed for +human consumption. + diff --git a/cli/report_directory_directory.md b/cli/report_directory_directory.md index 872b3d92..638b26a3 100644 --- a/cli/report_directory_directory.md +++ b/cli/report_directory_directory.md @@ -1,6 +1,9 @@ Enables report to be generated upon receiving the specified (or predefined) -signal to the running Node.js process, if `--experimental-report` is enabled. -The signal to trigger the report is specified through `--report-signal`. +signal to the running Node.js process. The signal to trigger the report is +specified through `--report-signal`. diff --git a/cli/report_signal_signal.md b/cli/report_signal_signal.md index 7942828f..cb8136c8 100644 --- a/cli/report_signal_signal.md +++ b/cli/report_signal_signal.md @@ -1,6 +1,9 @@ -Enables report to be generated on un-caught exceptions, if -`--experimental-report` is enabled. Useful when inspecting JavaScript stack in -conjunction with native stack and other runtime environment data. +Enables report to be generated on uncaught exceptions. Useful when inspecting +the JavaScript stack in conjunction with native stack and other runtime +environment data. diff --git a/cli/tls_keylog_file.md b/cli/tls_keylog_file.md index bbcacce9..82d81113 100644 --- a/cli/tls_keylog_file.md +++ b/cli/tls_keylog_file.md @@ -1,5 +1,5 @@ Log TLS key material to a file. The key material is in NSS `SSLKEYLOGFILE` diff --git a/cli/trace_exit.md b/cli/trace_exit.md index 4ed562cb..0ac7bd52 100644 --- a/cli/trace_exit.md +++ b/cli/trace_exit.md @@ -1,5 +1,5 @@ Prints a stack trace whenever an environment is exited proactively, diff --git a/cli/trace_sigint.md b/cli/trace_sigint.md new file mode 100644 index 00000000..2f4896c8 --- /dev/null +++ b/cli/trace_sigint.md @@ -0,0 +1,6 @@ + + +Prints a stack trace on SIGINT. + diff --git a/cli/trace_uncaught.md b/cli/trace_uncaught.md index 70cf2bd3..796b019f 100644 --- a/cli/trace_uncaught.md +++ b/cli/trace_uncaught.md @@ -1,5 +1,5 @@ Print stack traces for uncaught exceptions; usually, the stack trace associated diff --git a/cli/use_largepages_mode.md b/cli/use_largepages_mode.md new file mode 100644 index 00000000..6ddd92f9 --- /dev/null +++ b/cli/use_largepages_mode.md @@ -0,0 +1,15 @@ + + +Re-map the Node.js static code to large memory pages at startup. If supported on +the target system, this will cause the Node.js static code to be moved onto 2 +MiB pages instead of 4 KiB pages. + +The following values are valid for `mode`: +* `off`: No mapping will be attempted. This is the default. +* `on`: If supported by the OS, mapping will be attempted. Failure to map will + be ignored and a message will be printed to standard error. +* `silent`: If supported by the OS, mapping will be attempted. Failure to map + will be ignored and will not be reported. + diff --git a/cli/useful_v8_options.md b/cli/useful_v8_options.md new file mode 100644 index 00000000..ca230fe6 --- /dev/null +++ b/cli/useful_v8_options.md @@ -0,0 +1,10 @@ + +V8 has its own set of CLI options. Any V8 CLI option that is provided to `node` +will be passed on to V8 to handle. V8's options have _no stability guarantee_. +The V8 team themselves don't consider them to be part of their formal API, +and reserve the right to change them at any time. Likewise, they are not +covered by the Node.js stability guarantees. Many of the V8 +options are of interest only to V8 developers. Despite this, there is a small +set of V8 options that are widely applicable to Node.js, and they are +documented here: + diff --git a/cli/uv_threadpool_size_size.md b/cli/uv_threadpool_size_size.md index e6c0bc55..5d577abd 100644 --- a/cli/uv_threadpool_size_size.md +++ b/cli/uv_threadpool_size_size.md @@ -20,25 +20,3 @@ threadpool by setting the `'UV_THREADPOOL_SIZE'` environment variable to a value greater than `4` (its current default value). For more information, see the [libuv threadpool documentation][]. - - - - - - - - - - - - - - - - - - - - - - diff --git a/cluster/cluster_settings.md b/cluster/cluster_settings.md index af754bb1..2e5d922b 100644 --- a/cluster/cluster_settings.md +++ b/cluster/cluster_settings.md @@ -1,7 +1,7 @@ + +* `options`: {Object} + * `privateKey`: {KeyObject} + * `publicKey`: {KeyObject} +* Returns: {Buffer} + +Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. +Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` +(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + diff --git a/crypto/crypto_generatekeypair_type_options_callback.md b/crypto/crypto_generatekeypair_type_options_callback.md index d22784a1..da992e7b 100644 --- a/crypto/crypto_generatekeypair_type_options_callback.md +++ b/crypto/crypto_generatekeypair_type_options_callback.md @@ -1,6 +1,9 @@ * `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, - `'x25519'`, or `'x448'`. + `'x25519'`, `'x448'`, or `'dh'`. * `options`: {Object} * `modulusLength`: {number} Key size in bits (RSA, DSA). * `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`. * `divisorLength`: {number} Size of `q` in bits (DSA). * `namedCurve`: {string} Name of the curve to use (EC). + * `prime`: {Buffer} The prime parameter (DH). + * `primeLength`: {number} Prime length in bits (DH). + * `generator`: {number} Custom generator (DH). **Default:** `2`. + * `groupName`: {string} Diffie-Hellman group name (DH). See + [`crypto.getDiffieHellman()`][]. * `publicKeyEncoding`: {Object} See [`keyObject.export()`][]. * `privateKeyEncoding`: {Object} See [`keyObject.export()`][]. * `callback`: {Function} @@ -27,8 +35,8 @@ changes: * `publicKey`: {string | Buffer | KeyObject} * `privateKey`: {string | Buffer | KeyObject} -Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519 -and Ed448 are currently supported. +Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519, +Ed448, X25519, X448, and DH are currently supported. If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function behaves as if [`keyObject.export()`][] had been called on its result. Otherwise, diff --git a/crypto/crypto_generatekeypairsync_type_options.md b/crypto/crypto_generatekeypairsync_type_options.md index 3f642540..0f2e2866 100644 --- a/crypto/crypto_generatekeypairsync_type_options.md +++ b/crypto/crypto_generatekeypairsync_type_options.md @@ -1,6 +1,9 @@ -* `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, or `'ed448'`. +* `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, + `'x25519'`, `'x448'`, or `'dh'`. * `options`: {Object} * `modulusLength`: {number} Key size in bits (RSA, DSA). * `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`. * `divisorLength`: {number} Size of `q` in bits (DSA). * `namedCurve`: {string} Name of the curve to use (EC). + * `prime`: {Buffer} The prime parameter (DH). + * `primeLength`: {number} Prime length in bits (DH). + * `generator`: {number} Custom generator (DH). **Default:** `2`. + * `groupName`: {string} Diffie-Hellman group name (DH). See + [`crypto.getDiffieHellman()`][]. * `publicKeyEncoding`: {Object} See [`keyObject.export()`][]. * `privateKeyEncoding`: {Object} See [`keyObject.export()`][]. * Returns: {Object} * `publicKey`: {string | Buffer | KeyObject} * `privateKey`: {string | Buffer | KeyObject} -Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519 -and Ed448 are currently supported. +Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519, +Ed448, X25519, X448, and DH are currently supported. If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function behaves as if [`keyObject.export()`][] had been called on its result. Otherwise, diff --git a/crypto/crypto_getfips.md b/crypto/crypto_getfips.md index f391d70f..761d345a 100644 --- a/crypto/crypto_getfips.md +++ b/crypto/crypto_getfips.md @@ -2,6 +2,7 @@ added: v10.0.0 --> -* Returns: {boolean} `true` if and only if a FIPS compliant crypto provider is - currently in use. +* Returns: {number} `1` if and only if a FIPS compliant crypto provider is + currently in use, `0` otherwise. A future semver-major release may change + the return type of this API to a {boolean}. diff --git a/crypto/crypto_pbkdf2_password_salt_iterations_keylen_digest_callback.md b/crypto/crypto_pbkdf2_password_salt_iterations_keylen_digest_callback.md index 80c3906d..e9507dcd 100644 --- a/crypto/crypto_pbkdf2_password_salt_iterations_keylen_digest_callback.md +++ b/crypto/crypto_pbkdf2_password_salt_iterations_keylen_digest_callback.md @@ -1,6 +1,10 @@ * `privateKey` {Object | string | Buffer | KeyObject} - * `oaepHash` {string} The hash function to use for OAEP padding. + * `oaepHash` {string} The hash function to use for OAEP padding and MGF1. **Default:** `'sha1'` * `oaepLabel` {Buffer | TypedArray | DataView} The label to use for OAEP padding. If not specified, no label is used. diff --git a/crypto/crypto_publicencrypt_key_buffer.md b/crypto/crypto_publicencrypt_key_buffer.md index 5168fa3e..e4b5de0d 100644 --- a/crypto/crypto_publicencrypt_key_buffer.md +++ b/crypto/crypto_publicencrypt_key_buffer.md @@ -14,7 +14,7 @@ changes: * `key` {Object | string | Buffer | KeyObject} * `key` {string | Buffer | KeyObject} A PEM encoded public or private key. - * `oaepHash` {string} The hash function to use for OAEP padding. + * `oaepHash` {string} The hash function to use for OAEP padding and MGF1. **Default:** `'sha1'` * `oaepLabel` {Buffer | TypedArray | DataView} The label to use for OAEP padding. If not specified, no label is used. diff --git a/crypto/hash_copy_options.md b/crypto/hash_copy_options.md index 6b2c9475..9476c0b0 100644 --- a/crypto/hash_copy_options.md +++ b/crypto/hash_copy_options.md @@ -1,5 +1,5 @@ * `options` {Object} [`stream.transform` options][] diff --git a/crypto/keyobject_asymmetrickeytype.md b/crypto/keyobject_asymmetrickeytype.md index 1aa0e814..e57c030d 100644 --- a/crypto/keyobject_asymmetrickeytype.md +++ b/crypto/keyobject_asymmetrickeytype.md @@ -1,6 +1,9 @@ -Type: Runtime +Type: End-of-Life -The `OutgoingMessage.prototype.flush()` method is deprecated. Use +`OutgoingMessage.prototype.flush()` has been removed. Use `OutgoingMessage.prototype.flushHeaders()` instead. diff --git a/deprecations/dep0003_writablestate_buffer.md b/deprecations/dep0003_writablestate_buffer.md index f7c949f9..128ee066 100644 --- a/deprecations/dep0003_writablestate_buffer.md +++ b/deprecations/dep0003_writablestate_buffer.md @@ -1,5 +1,8 @@ -Type: Runtime +Type: End-of-Life -The `_writableState.buffer` property is deprecated. Use the -`_writableState.getBuffer()` method instead. +The `_writableState.buffer` has been removed. Use `_writableState.getBuffer()` +instead. diff --git a/deprecations/dep0009_crypto_pbkdf2_without_digest.md b/deprecations/dep0009_crypto_pbkdf2_without_digest.md index 168d7430..8e3ebd62 100644 --- a/deprecations/dep0009_crypto_pbkdf2_without_digest.md +++ b/deprecations/dep0009_crypto_pbkdf2_without_digest.md @@ -1,5 +1,8 @@ -Type: Runtime +Type: End-of-Life Use of the [`crypto.pbkdf2()`][] API without specifying a digest was deprecated in Node.js 6.0 because the method defaulted to using the non-recommended @@ -23,7 +26,9 @@ Node.js 8.0.0, calling `crypto.pbkdf2()` or `crypto.pbkdf2Sync()` with `digest` set to `undefined` will throw a `TypeError`. Beginning in Node.js v11.0.0, calling these functions with `digest` set to -`null` will print a deprecation warning to align with the behavior when `digest` +`null` would print a deprecation warning to align with the behavior when `digest` is `undefined`. +Now, however, passing either `undefined` or `null` will throw a `TypeError`. + diff --git a/deprecations/dep0016_global_root.md b/deprecations/dep0016_global_root.md index 09b201e7..d174baac 100644 --- a/deprecations/dep0016_global_root.md +++ b/deprecations/dep0016_global_root.md @@ -1,5 +1,8 @@ -Type: Runtime +Type: End-of-Life -The `GLOBAL` and `root` aliases for the `global` property are deprecated -and should no longer be used. +The `GLOBAL` and `root` aliases for the `global` property were deprecated +in Node.js 6.0.0 and have since been removed. diff --git a/deprecations/dep0022_os_tmpdir.md b/deprecations/dep0022_os_tmpdir.md index 3e0461b9..20b73d38 100644 --- a/deprecations/dep0022_os_tmpdir.md +++ b/deprecations/dep0022_os_tmpdir.md @@ -1,12 +1,16 @@ -Type: Runtime +Type: End-of-Life -The `os.tmpDir()` API is deprecated. Please use [`os.tmpdir()`][] instead. +The `os.tmpDir()` API was deprecated in Node.js 7.0.0 and has since been +removed. Please use [`os.tmpdir()`][] instead. diff --git a/deprecations/dep0129_childprocess_channel.md b/deprecations/dep0129_childprocess_channel.md index 95d1c542..b6207ec1 100644 --- a/deprecations/dep0129_childprocess_channel.md +++ b/deprecations/dep0129_childprocess_channel.md @@ -1,11 +1,14 @@ -Type: Documentation-only +Type: Runtime The `_channel` property of child process objects returned by `spawn()` and similar functions is not intended for public use. Use `ChildProcess.channel` diff --git a/deprecations/dep0130_module_createrequirefrompath.md b/deprecations/dep0130_module_createrequirefrompath.md index 84c1e15c..e3cb79e4 100644 --- a/deprecations/dep0130_module_createrequirefrompath.md +++ b/deprecations/dep0130_module_createrequirefrompath.md @@ -1,12 +1,16 @@ -Type: Documentation-only +Type: Runtime -Module.createRequireFromPath() is deprecated. Please use [`module.createRequire()`][] instead. +Module.createRequireFromPath() is deprecated. Please use +[`module.createRequire()`][] instead. diff --git a/deprecations/dep0131_legacy_http_parser.md b/deprecations/dep0131_legacy_http_parser.md index 1e39a7be..8199f9d9 100644 --- a/deprecations/dep0131_legacy_http_parser.md +++ b/deprecations/dep0131_legacy_http_parser.md @@ -1,14 +1,18 @@ -Type: Documentation-only +Type: End-of-Life The legacy HTTP parser, used by default in versions of Node.js prior to 12.0.0, -is deprecated. This deprecation applies to users of the -[`--http-parser=legacy`][] command-line flag. +is deprecated and has been removed in v13.0.0. Prior to v13.0.0, the +`--http-parser=legacy` command-line flag could be used to revert to using the +legacy parser. diff --git a/deprecations/dep0134_process_tickcallback.md b/deprecations/dep0134_process_tickcallback.md index 2a453bf1..48dc757c 100644 --- a/deprecations/dep0134_process_tickcallback.md +++ b/deprecations/dep0134_process_tickcallback.md @@ -9,4 +9,4 @@ Type: Documentation-only (supports [`--pending-deprecation`][]) The `process._tickCallback` property was never documented as an officially supported API. - + diff --git a/deprecations/dep0135_writestream_open_and_readstream_open_are_internal.md b/deprecations/dep0135_writestream_open_and_readstream_open_are_internal.md new file mode 100644 index 00000000..3f6c5a6d --- /dev/null +++ b/deprecations/dep0135_writestream_open_and_readstream_open_are_internal.md @@ -0,0 +1,14 @@ + + +Type: Runtime + +[`WriteStream.open()`][] and [`ReadStream.open()`][] are undocumented internal +APIs that do not make sense to use in userland. File streams should always be +opened through their corresponding factory methods [`fs.createWriteStream()`][] +and [`fs.createReadStream()`][]) or by passing a file descriptor in options. + + diff --git a/deprecations/dep0136_http_finished.md b/deprecations/dep0136_http_finished.md index d7c45848..84b0e3bd 100644 --- a/deprecations/dep0136_http_finished.md +++ b/deprecations/dep0136_http_finished.md @@ -1,6 +1,6 @@ @@ -17,115 +17,4 @@ accordingly instead to avoid the ambigiuty. To maintain existing behaviour `response.finished` should be replaced with `response.writableEnded`. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + diff --git a/deprecations/dep0137_closing_fs_filehandle_on_garbage_collection.md b/deprecations/dep0137_closing_fs_filehandle_on_garbage_collection.md new file mode 100644 index 00000000..6c20b727 --- /dev/null +++ b/deprecations/dep0137_closing_fs_filehandle_on_garbage_collection.md @@ -0,0 +1,30 @@ + + +Type: Runtime + +Allowing a [`fs.FileHandle`][] object to be closed on garbage collection is +deprecated. In the future, doing so may result in a thrown error that will +terminate the process. + +Please ensure that all `fs.FileHandle` objects are explicitly closed using +`FileHandle.prototype.close()` when the `fs.FileHandle` is no longer needed: + +```js +const fsPromises = require('fs').promises; +async function openAndClose() { + let filehandle; + try { + filehandle = await fsPromises.open('thefile.txt', 'r'); + } finally { + if (filehandle !== undefined) + await filehandle.close(); + } +} +``` + + diff --git a/deprecations/dep0138_process_mainmodule.md b/deprecations/dep0138_process_mainmodule.md new file mode 100644 index 00000000..d9eb0c0f --- /dev/null +++ b/deprecations/dep0138_process_mainmodule.md @@ -0,0 +1,17 @@ + + +Type: Documentation-only + +[`process.mainModule`][] is a CommonJS-only feature while `process` global +object is shared with non-CommonJS environment. Its use within ECMAScript +modules is unsupported. + +It is deprecated in favor of [`require.main`][], because it serves the same +purpose and is only available on CommonJS environment. + + diff --git a/deprecations/dep0139_process_umask_with_no_arguments.md b/deprecations/dep0139_process_umask_with_no_arguments.md new file mode 100644 index 00000000..94a7268f --- /dev/null +++ b/deprecations/dep0139_process_umask_with_no_arguments.md @@ -0,0 +1,132 @@ + + +Type: Documentation-only + +Calling `process.umask()` with no argument causes the process-wide umask to be +written twice. This introduces a race condition between threads, and is a +potential security vulnerability. There is no safe, cross-platform alternative +API. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/deprecations/dep0xxx_process_umask_with_no_arguments.md b/deprecations/dep0xxx_process_umask_with_no_arguments.md new file mode 100644 index 00000000..fb0e6a66 --- /dev/null +++ b/deprecations/dep0xxx_process_umask_with_no_arguments.md @@ -0,0 +1,132 @@ + + +Type: Documentation-only + +Calling `process.umask()` with no argument causes the process-wide umask to be +written twice. This introduces a race condition between threads, and is a +potential security vulnerability. There is no safe, cross-platform alternative +API. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dgram/event_listening.md b/dgram/event_listening.md index 83e71b9d..f30bfb28 100644 --- a/dgram/event_listening.md +++ b/dgram/event_listening.md @@ -2,6 +2,7 @@ added: v0.1.99 --> -当一个 socket 开始监听数据包信息时,`'listening'` 事件将被触发。 -该事件会在创建 UDP socket 之后被立即触发。 +每当 `dgram.Socket` 可被寻址且可以接收数据时,就会触发 `'listening'` 事件。 +这会发生在,显式地使用 `socket.bind()`、或者隐式地使用 `socket.send()` 第一次发送数据。 +在 `dgram.Socket` 开始监听之前,底层的系统资源并不存在,且诸如 `socket.address()` 和 `socket.setTTL()` 之类的调用都会失败。 diff --git a/dgram/socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface.md b/dgram/socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface.md index e00efafe..d72affbb 100644 --- a/dgram/socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface.md +++ b/dgram/socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface.md @@ -1,5 +1,5 @@ * `sourceAddress` {string} * `groupAddress` {string} diff --git a/dgram/socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface.md b/dgram/socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface.md index 420066b1..ae2a89a5 100644 --- a/dgram/socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface.md +++ b/dgram/socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface.md @@ -1,5 +1,5 @@ * `sourceAddress` {string} diff --git a/dns/dns.md b/dns/dns.md index a7fdfde6..0dbbf9aa 100644 --- a/dns/dns.md +++ b/dns/dns.md @@ -6,7 +6,7 @@ `dns` 模块用于启用名称解析。 例如,使用它来查找主机名的 IP 地址。 -尽管以域名系统(DNS)命名,但它并不总是使用 DNS 协议进行查找。 +尽管以[域名系统(DNS)][Domain Name System (DNS)]命名,但它并不总是使用 DNS 协议进行查找。 [`dns.lookup()`] 使用操作系统功能来执行名称解析。 它可能不需要执行任何网络通信。 希望以与同一操作系统上其他应用程序相同的方式执行名称解析的开发者应使用 [`dns.lookup()`]。 diff --git a/dns/supported_getaddrinfo_flags.md b/dns/supported_getaddrinfo_flags.md index f96e661f..02e14106 100644 --- a/dns/supported_getaddrinfo_flags.md +++ b/dns/supported_getaddrinfo_flags.md @@ -1,6 +1,13 @@ + 以下内容可以作为 hints 标志传给 [`dns.lookup()`]。 -- `dns.ADDRCONFIG`: 返回当前系统支持的地址类型。例如,如果当前系统至少配置了一个 IPv4 地址,则返回 IPv4 地址。不考虑回环地址。 -- `dns.V4MAPPED`: 如果指定了 IPv6 地址族,但是没有找到 IPv6 地址,则返回 IPv4 映射的 IPv6 地址。在有些操作系统中不支持(例如 FreeBSD 10.1)。 +* `dns.ADDRCONFIG`: 返回当前系统支持的地址类型。例如,如果当前系统至少配置了一个 IPv4 地址,则返回 IPv4 地址。不考虑回环地址。 +* `dns.V4MAPPED`: 如果指定了 IPv6 地址族,但是没有找到 IPv6 地址,则返回 IPv4 映射的 IPv6 地址。在有些操作系统中不支持(例如 FreeBSD 10.1)。 +* `dns.ALL`: 如果指定了 `dns.V4MAPPED`,则返回解析的 IPv6 地址以及 IPv4 映射的 IPv6 地址。 diff --git a/embedding/c_embedder_api.md b/embedding/c_embedder_api.md new file mode 100644 index 00000000..0152a7ea --- /dev/null +++ b/embedding/c_embedder_api.md @@ -0,0 +1,15 @@ + + + +Node.js provides a number of C++ APIs that can be used to execute JavaScript +in a Node.js environment from other C++ software. + +The documentation for these APIs can be found in [src/node.h][] in the Node.js +source tree. In addition to the APIs exposed by Node.js, some required concepts +are provided by the V8 embedder API. + +Because using Node.js as an embedded library is different from writing code +that is executed by Node.js, breaking changes do not follow typical Node.js +[deprecation policy][] and may occur on each semver-major release without prior +warning. + diff --git a/embedding/example_embedding_application.md b/embedding/example_embedding_application.md new file mode 100644 index 00000000..dbff8703 --- /dev/null +++ b/embedding/example_embedding_application.md @@ -0,0 +1,8 @@ + +The following sections will provide an overview over how to use these APIs +to create an application from scratch that will perform the equivalent of +`node -e `, i.e. that will take a piece of JavaScript and run it in +a Node.js-specific environment. + +The full code can be found [in the Node.js source tree][embedtest.cc]. + diff --git a/embedding/per_instance_state.md b/embedding/per_instance_state.md new file mode 100644 index 00000000..5c45b30c --- /dev/null +++ b/embedding/per_instance_state.md @@ -0,0 +1,158 @@ + +Node.js has a concept of a “Node.js instance”, that is commonly being referred +to as `node::Environment`. Each `node::Environment` is associated with: + +* Exactly one `v8::Isolate`, i.e. one JS Engine instance, +* Exactly one `uv_loop_t`, i.e. one event loop, and +* A number of `v8::Context`s, but exactly one main `v8::Context`. +* One `node::IsolateData` instance that contains information that could be + shared by multiple `node::Environment`s that use the same `v8::Isolate`. + Currently, no testing if performed for this scenario. + +In order to set up a `v8::Isolate`, an `v8::ArrayBuffer::Allocator` needs +to be provided. One possible choice is the default Node.js allocator, which +can be created through `node::ArrayBufferAllocator::Create()`. Using the Node.js +allocator allows minor performance optimizations when addons use the Node.js +C++ `Buffer` API, and is required in order to track `ArrayBuffer` memory in +[`process.memoryUsage()`][]. + +Additionally, each `v8::Isolate` that is used for a Node.js instance needs to +be registered and unregistered with the `MultiIsolatePlatform` instance, if one +is being used, in order for the platform to know which event loop to use +for tasks scheduled by the `v8::Isolate`. + +The `node::NewIsolate()` helper function creates a `v8::Isolate`, +sets it up with some Node.js-specific hooks (e.g. the Node.js error handler), +and registers it with the platform automatically. + +```c++ +int RunNodeInstance(MultiIsolatePlatform* platform, + const std::vector& args, + const std::vector& exec_args) { + int exit_code = 0; + // Set up a libuv event loop. + uv_loop_t loop; + int ret = uv_loop_init(&loop); + if (ret != 0) { + fprintf(stderr, "%s: Failed to initialize loop: %s\n", + args[0].c_str(), + uv_err_name(ret)); + return 1; + } + + std::shared_ptr allocator = + ArrayBufferAllocator::Create(); + + Isolate* isolate = NewIsolate(allocator, &loop, platform); + if (isolate == nullptr) { + fprintf(stderr, "%s: Failed to initialize V8 Isolate\n", args[0].c_str()); + return 1; + } + + { + Locker locker(isolate); + Isolate::Scope isolate_scope(isolate); + + // Create a node::IsolateData instance that will later be released using + // node::FreeIsolateData(). + std::unique_ptr isolate_data( + node::CreateIsolateData(isolate, &loop, platform, allocator.get()), + node::FreeIsolateData); + + // Set up a new v8::Context. + HandleScope handle_scope(isolate); + Local context = node::NewContext(isolate); + if (context.IsEmpty()) { + fprintf(stderr, "%s: Failed to initialize V8 Context\n", args[0].c_str()); + return 1; + } + + // The v8::Context needs to be entered when node::CreateEnvironment() and + // node::LoadEnvironment() are being called. + Context::Scope context_scope(context); + + // Create a node::Environment instance that will later be released using + // node::FreeEnvironment(). + std::unique_ptr env( + node::CreateEnvironment(isolate_data.get(), context, args, exec_args), + node::FreeEnvironment); + + // Set up the Node.js instance for execution, and run code inside of it. + // There is also a variant that takes a callback and provides it with + // the `require` and `process` objects, so that it can manually compile + // and run scripts as needed. + // The `require` function inside this script does *not* access the file + // system, and can only load built-in Node.js modules. + // `module.createRequire()` is being used to create one that is able to + // load files from the disk, and uses the standard CommonJS file loader + // instead of the internal-only `require` function. + MaybeLocal loadenv_ret = node::LoadEnvironment( + env.get(), + "const publicRequire =" + " require('module').createRequire(process.cwd() + '/');" + "globalThis.require = publicRequire;" + "require('vm').runInThisContext(process.argv[1]);"); + + if (loadenv_ret.IsEmpty()) // There has been a JS exception. + return 1; + + { + // SealHandleScope protects against handle leaks from callbacks. + SealHandleScope seal(isolate); + bool more; + do { + uv_run(&loop, UV_RUN_DEFAULT); + + // V8 tasks on background threads may end up scheduling new tasks in the + // foreground, which in turn can keep the event loop going. For example, + // WebAssembly.compile() may do so. + platform->DrainTasks(isolate); + + // If there are new tasks, continue. + more = uv_loop_alive(&loop); + if (more) continue; + + // node::EmitBeforeExit() is used to emit the 'beforeExit' event on + // the `process` object. + node::EmitBeforeExit(env.get()); + + // 'beforeExit' can also schedule new work that keeps the event loop + // running. + more = uv_loop_alive(&loop); + } while (more == true); + } + + // node::EmitExit() returns the current exit code. + exit_code = node::EmitExit(env.get()); + + // node::Stop() can be used to explicitly stop the event loop and keep + // further JavaScript from running. It can be called from any thread, + // and will act like worker.terminate() if called from another thread. + node::Stop(env.get()); + } + + // Unregister the Isolate with the platform and add a listener that is called + // when the Platform is done cleaning up any state it had associated with + // the Isolate. + bool platform_finished = false; + platform->AddIsolateFinishedCallback(isolate, [](void* data) { + *static_cast(data) = true; + }, &platform_finished); + platform->UnregisterIsolate(isolate); + isolate->Dispose(); + + // Wait until the platform has cleaned up all relevant resources. + while (!platform_finished) + uv_run(&loop, UV_RUN_ONCE); + int err = uv_loop_close(&loop); + assert(err == 0); + + return exit_code; +} +``` + + + + + + diff --git a/embedding/setting_up_per_process_state.md b/embedding/setting_up_per_process_state.md new file mode 100644 index 00000000..6f0d86d9 --- /dev/null +++ b/embedding/setting_up_per_process_state.md @@ -0,0 +1,41 @@ + +Node.js requires some per-process state management in order to run: + +* Arguments parsing for Node.js [CLI options][], +* V8 per-process requirements, such as a `v8::Platform` instance. + +The following example shows how these can be set up. Some class names are from +the `node` and `v8` C++ namespaces, respectively. + +```c++ +int main(int argc, char** argv) { + std::vector args(argv, argv + argc); + std::vector exec_args; + std::vector errors; + // Parse Node.js CLI options, and print any errors that have occurred while + // trying to parse them. + int exit_code = node::InitializeNodeWithArgs(&args, &exec_args, &errors); + for (const std::string& error : errors) + fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str()); + if (exit_code != 0) { + return exit_code; + } + + // Create a v8::Platform instance. `MultiIsolatePlatform::Create()` is a way + // to create a v8::Platform instance that Node.js can use when creating + // Worker threads. When no `MultiIsolatePlatform` instance is present, + // Worker threads are disabled. + std::unique_ptr platform = + MultiIsolatePlatform::Create(4); + V8::InitializePlatform(platform.get()); + V8::Initialize(); + + // See below for the contents of this function. + int ret = RunNodeInstance(platform.get(), args, exec_args); + + V8::Dispose(); + V8::ShutdownPlatform(); + return ret; +} +``` + diff --git a/errors/class_systemerror.md b/errors/class_systemerror.md index 6080896b..eae5008b 100644 --- a/errors/class_systemerror.md +++ b/errors/class_systemerror.md @@ -11,7 +11,7 @@ attempts to read a file that does not exist. * `code` {string} The string error code * `dest` {string} If present, the file path destination when reporting a file system error -* `errno` {number|string} The system-provided error number +* `errno` {number} The system-provided error number * `info` {Object} If present, extra details about the error condition * `message` {string} A system-provided human-readable description of the error * `path` {string} If present, the file path when reporting a file system error diff --git a/errors/err_console_writable_stream.md b/errors/err_console_writable_stream.md index 861e8cf6..23ddc803 100644 --- a/errors/err_console_writable_stream.md +++ b/errors/err_console_writable_stream.md @@ -2,4 +2,4 @@ `Console` was instantiated without `stdout` stream, or `Console` has a non-writable `stdout` or `stderr` stream. - + diff --git a/errors/err_context_not_initialized.md b/errors/err_context_not_initialized.md new file mode 100644 index 00000000..6f152c80 --- /dev/null +++ b/errors/err_context_not_initialized.md @@ -0,0 +1,7 @@ + +The vm context passed into the API is not yet initialized. This could happen +when an error occurs (and is caught) during the creation of the +context, for example, when the allocation fails or the maximum call stack +size is reached when the context is created. + + diff --git a/errors/err_crypto_hash_update_failed.md b/errors/err_crypto_hash_update_failed.md index ea9842f3..a873284f 100644 --- a/errors/err_crypto_hash_update_failed.md +++ b/errors/err_crypto_hash_update_failed.md @@ -1,4 +1,4 @@ [`hash.update()`][] failed for any reason. This should rarely, if ever, happen. - + diff --git a/errors/err_crypto_incompatible_key.md b/errors/err_crypto_incompatible_key.md new file mode 100644 index 00000000..99e21c7c --- /dev/null +++ b/errors/err_crypto_incompatible_key.md @@ -0,0 +1,4 @@ + +The given crypto keys are incompatible with the attempted operation. + + diff --git a/errors/err_crypto_timing_safe_equal_length.md b/errors/err_crypto_timing_safe_equal_length.md index dbac2703..e0b9ffda 100644 --- a/errors/err_crypto_timing_safe_equal_length.md +++ b/errors/err_crypto_timing_safe_equal_length.md @@ -2,4 +2,4 @@ [`crypto.timingSafeEqual()`][] was called with `Buffer`, `TypedArray`, or `DataView` arguments of different lengths. - + diff --git a/errors/err_crypto_unknown_cipher.md b/errors/err_crypto_unknown_cipher.md new file mode 100644 index 00000000..d2bddbd2 --- /dev/null +++ b/errors/err_crypto_unknown_cipher.md @@ -0,0 +1,4 @@ + +An unknown cipher was specified. + + diff --git a/errors/err_crypto_unknown_dh_group.md b/errors/err_crypto_unknown_dh_group.md new file mode 100644 index 00000000..1e88b258 --- /dev/null +++ b/errors/err_crypto_unknown_dh_group.md @@ -0,0 +1,5 @@ + +An unknown Diffie-Hellman group name was given. See +[`crypto.getDiffieHellman()`][] for a list of valid group names. + + diff --git a/errors/err_encoding_not_supported.md b/errors/err_encoding_not_supported.md index 3b94418c..1b5d4b25 100644 --- a/errors/err_encoding_not_supported.md +++ b/errors/err_encoding_not_supported.md @@ -1,4 +1,4 @@ 提供给 `TextDecoder()` API 的字符编码不是 [WHATWG 支持的字符编码][WHATWG Supported Encodings]。 - + diff --git a/errors/err_execution_environment_not_available.md b/errors/err_execution_environment_not_available.md new file mode 100644 index 00000000..ba31e4b7 --- /dev/null +++ b/errors/err_execution_environment_not_available.md @@ -0,0 +1,6 @@ + +The JS execution context is not associated with a Node.js environment. +This may occur when Node.js is used as an embedded library and some hooks +for the JS engine are not set up properly. + + diff --git a/errors/err_feature_unavailable_on_platform.md b/errors/err_feature_unavailable_on_platform.md new file mode 100644 index 00000000..3c0447d0 --- /dev/null +++ b/errors/err_feature_unavailable_on_platform.md @@ -0,0 +1,5 @@ + +Used when a feature that is not available +to the current platform which is running Node.js is used. + + diff --git a/errors/err_missing_dynamic_instantiate_hook.md b/errors/err_missing_dynamic_instantiate_hook.md index 5518afff..c48c0200 100644 --- a/errors/err_missing_dynamic_instantiate_hook.md +++ b/errors/err_missing_dynamic_instantiate_hook.md @@ -4,4 +4,4 @@ An [ES Module][] loader hook specified `format: 'dynamic'` but did not provide a `dynamicInstantiate` hook. - + diff --git a/errors/err_missing_dynamic_instantiate_hook_1.md b/errors/err_missing_dynamic_instantiate_hook_1.md index f0539490..c66225ab 100644 --- a/errors/err_missing_dynamic_instantiate_hook_1.md +++ b/errors/err_missing_dynamic_instantiate_hook_1.md @@ -2,4 +2,4 @@ Used when an [ES Module][] loader hook specifies `format: 'dynamic'` but does not provide a `dynamicInstantiate` hook. - + diff --git a/errors/err_missing_option.md b/errors/err_missing_option.md new file mode 100644 index 00000000..e63911c8 --- /dev/null +++ b/errors/err_missing_option.md @@ -0,0 +1,5 @@ + +For APIs that accept options objects, some options might be mandatory. This code +is thrown if a required option is missing. + + diff --git a/errors/err_package_path_not_exported.md b/errors/err_package_path_not_exported.md index 45e7f53e..587ea13b 100644 --- a/errors/err_package_path_not_exported.md +++ b/errors/err_package_path_not_exported.md @@ -3,4 +3,4 @@ The `package.json` [exports][] field does not export the requested subpath. Because exports are encapsulated, private internal modules that are not exported cannot be imported through the package resolution, unless using an absolute URL. - + diff --git a/errors/err_parse_history_data.md b/errors/err_parse_history_data.md index 75e4bd18..75bfb139 100644 --- a/errors/err_parse_history_data.md +++ b/errors/err_parse_history_data.md @@ -5,4 +5,4 @@ removed: v10.0.0 The `repl` module was unable to parse data from the REPL history file. - + diff --git a/errors/err_proto_access.md b/errors/err_proto_access.md new file mode 100644 index 00000000..d031c4b5 --- /dev/null +++ b/errors/err_proto_access.md @@ -0,0 +1,7 @@ + +Accessing `Object.prototype.__proto__` has been forbidden using +[`--disable-proto=throw`][]. [`Object.getPrototypeOf`][] and +[`Object.setPrototypeOf`][] should be used to get and set the prototype of an +object. + + diff --git a/errors/err_socket_buffer_size.md b/errors/err_socket_buffer_size.md index eacd4b75..2c3ad9c8 100644 --- a/errors/err_socket_buffer_size.md +++ b/errors/err_socket_buffer_size.md @@ -2,4 +2,4 @@ While using [`dgram.createSocket()`][], the size of the receive or send `Buffer` could not be determined. - + diff --git a/errors/err_socket_cannot_send.md b/errors/err_socket_cannot_send.md index f8df0573..593523ed 100644 --- a/errors/err_socket_cannot_send.md +++ b/errors/err_socket_cannot_send.md @@ -1,4 +1,8 @@ + Data could be sent on a socket. - + diff --git a/errors/err_stream_already_finished.md b/errors/err_stream_already_finished.md new file mode 100644 index 00000000..a118e7ab --- /dev/null +++ b/errors/err_stream_already_finished.md @@ -0,0 +1,5 @@ + +A stream method was called that cannot complete because the stream was +finished. + + diff --git a/errors/err_stream_destroyed.md b/errors/err_stream_destroyed.md index ea6af656..29781c89 100644 --- a/errors/err_stream_destroyed.md +++ b/errors/err_stream_destroyed.md @@ -2,4 +2,4 @@ A stream method was called that cannot complete because the stream was destroyed using `stream.destroy()`. - + diff --git a/errors/err_tls_handshake_timeout.md b/errors/err_tls_handshake_timeout.md index 561c47e9..145fed97 100644 --- a/errors/err_tls_handshake_timeout.md +++ b/errors/err_tls_handshake_timeout.md @@ -2,4 +2,4 @@ A TLS/SSL handshake timed out. In this case, the server must also abort the connection. - + diff --git a/errors/err_tls_invalid_context.md b/errors/err_tls_invalid_context.md index f2157a0d..d05a7aef 100644 --- a/errors/err_tls_invalid_context.md +++ b/errors/err_tls_invalid_context.md @@ -1,7 +1,7 @@ The context must be a `SecureContext`. - + diff --git a/errors/err_tls_invalid_state.md b/errors/err_tls_invalid_state.md new file mode 100644 index 00000000..d0cd7291 --- /dev/null +++ b/errors/err_tls_invalid_state.md @@ -0,0 +1,8 @@ + + +The TLS socket must be connected and securily established. Ensure the 'secure' +event is emitted before continuing. + + diff --git a/errors/err_tty_writable_not_readable.md b/errors/err_tty_writable_not_readable.md index a9b8591b..5333ee33 100644 --- a/errors/err_tty_writable_not_readable.md +++ b/errors/err_tty_writable_not_readable.md @@ -60,6 +60,11 @@ such as `process.stdout.on('data')`. + + + + + diff --git a/errors/err_vm_module_already_linked.md b/errors/err_vm_module_already_linked.md index 82da7e9a..8e9e0a98 100644 --- a/errors/err_vm_module_already_linked.md +++ b/errors/err_vm_module_already_linked.md @@ -6,4 +6,4 @@ the following reasons: * It is being linked (`linkingStatus` is `'linking'`) * Linking has failed for this module (`linkingStatus` is `'errored'`) - + diff --git a/errors/err_vm_module_cached_data_rejected.md b/errors/err_vm_module_cached_data_rejected.md new file mode 100644 index 00000000..b94a0d62 --- /dev/null +++ b/errors/err_vm_module_cached_data_rejected.md @@ -0,0 +1,4 @@ + +The `cachedData` option passed to a module constructor is invalid. + + diff --git a/errors/err_vm_module_cannot_create_cached_data.md b/errors/err_vm_module_cannot_create_cached_data.md new file mode 100644 index 00000000..b0a9f224 --- /dev/null +++ b/errors/err_vm_module_cannot_create_cached_data.md @@ -0,0 +1,4 @@ + +Cached data cannot be created for modules which have already been evaluated. + + diff --git a/errors/err_worker_invalid_exec_argv.md b/errors/err_worker_invalid_exec_argv.md index 654d8fae..3494bed6 100644 --- a/errors/err_worker_invalid_exec_argv.md +++ b/errors/err_worker_invalid_exec_argv.md @@ -2,4 +2,4 @@ The `execArgv` option passed to the `Worker` constructor contains invalid flags. - + diff --git a/errors/err_worker_not_running.md b/errors/err_worker_not_running.md new file mode 100644 index 00000000..6c73fbde --- /dev/null +++ b/errors/err_worker_not_running.md @@ -0,0 +1,4 @@ + +An operation failed because the `Worker` instance is not currently running. + + diff --git a/errors/error_errno.md b/errors/error_errno.md index b7929931..98bb4be4 100644 --- a/errors/error_errno.md +++ b/errors/error_errno.md @@ -1,8 +1,10 @@ -* {string|number} +* {number} + +`error.errno` 属性是一个负数,对应 [`libuv 错误处理`][`libuv Error handling`] 中定义的错误码。 + +在 Windows 上,系统提供的错误码由 libuv 进行规范化。 + +要获取错误码的字符串表示形式,则使用 [`util.getSystemErrorName(error.errno)`]。 -`error.errno` 属性是一个数值或字符串。 -如果返回一个数值,则数值是一个负数,对应 [`libuv 错误处理`][`libuv Error handling`] 中定义的错误码。 -详见 libuv `errno.h` 头文件(Node.js 源代码中的 `deps/uv/include/uv/errno.h`)。 -如果返回一个字符串,则同 `error.code`。 diff --git a/esm/code_getglobalpreloadcode_code_hook.md b/esm/code_getglobalpreloadcode_code_hook.md index c65c4926..8b8cb9a0 100644 --- a/esm/code_getglobalpreloadcode_code_hook.md +++ b/esm/code_getglobalpreloadcode_code_hook.md @@ -24,7 +24,7 @@ console.log('I just set some globals!'); const { createRequire } = getBuiltin('module'); -const require = createRequire(process.cwd + '/'); +const require = createRequire(process.cwd() + '/'); // [...] `; } diff --git a/esm/code_resolve_code_hook.md b/esm/code_resolve_code_hook.md index e9d77756..ba47c4a2 100644 --- a/esm/code_resolve_code_hook.md +++ b/esm/code_resolve_code_hook.md @@ -7,11 +7,22 @@ and parent URL. The module specifier is the string in an `import` statement or `import()` expression, and the parent URL is the URL of the module that imported this one, or `undefined` if this is the main entry point for the application. +The `conditions` property on the `context` is an array of conditions for +[Conditional Exports][] that apply to this resolution request. They can be used +for looking up conditional mappings elsewhere or to modify the list when calling +the default resolution logic. + +The [current set of Node.js default conditions][Conditional Exports] will always +be in the `context.conditions` list passed to the hook. If the hook wants to +ensure Node.js-compatible resolution logic, all items from this default +condition list **must** be passed through to the `defaultResolve` function. + ```js /** * @param {string} specifier * @param {object} context * @param {string} context.parentURL + * @param {string[]} context.conditions * @param {function} defaultResolve * @returns {object} response * @returns {string} response.url @@ -26,6 +37,14 @@ export async function resolve(specifier, context, defaultResolve) { new URL(specifier, parentURL).href : new URL(specifier).href }; } + if (anotherCondition) { + // When calling the defaultResolve, the arguments can be modified. In this + // case it's adding another value for matching conditional exports. + return defaultResolve(specifier, { + ...context, + conditions: [...context.conditions, 'another-condition'], + }); + } // Defer to Node.js for all other specifiers. return defaultResolve(specifier, context, defaultResolve); } diff --git a/esm/code_transformsource_code_hook.md b/esm/code_transformsource_code_hook.md index 5cc6b265..91337776 100644 --- a/esm/code_transformsource_code_hook.md +++ b/esm/code_transformsource_code_hook.md @@ -1,8 +1,4 @@ -```console -NODE_OPTIONS='--experimental-modules --experimental-loader ./custom-loader.mjs' node x.js -``` - > Note: The loaders API is being redesigned. This hook may disappear or its > signature may change. Do not rely on the API described below. diff --git a/esm/customizing_esm_specifier_resolution_algorithm.md b/esm/customizing_esm_specifier_resolution_algorithm.md index 9e0b4489..b5f32c49 100644 --- a/esm/customizing_esm_specifier_resolution_algorithm.md +++ b/esm/customizing_esm_specifier_resolution_algorithm.md @@ -11,11 +11,11 @@ automatic extension resolution and importing from directories that include an index file use the `node` mode. ```bash -$ node --experimental-modules index.mjs +$ node index.mjs success! -$ node --experimental-modules index #Failure! +$ node index # Failure! Error: Cannot find module -$ node --experimental-modules --experimental-specifier-resolution=node index +$ node --experimental-specifier-resolution=node index success! ``` diff --git a/esm/enabling.md b/esm/enabling.md index 57ac49c7..d5fd8268 100644 --- a/esm/enabling.md +++ b/esm/enabling.md @@ -1,12 +1,9 @@ -The `--experimental-modules` flag can be used to enable support for -ECMAScript modules (ES modules). - -Once enabled, Node.js will treat the following as ES modules when passed to -`node` as the initial input, or when referenced by `import` statements within -ES module code: +Experimental support for ECMAScript modules is enabled by default. +Node.js will treat the following as ES modules when passed to `node` as the +initial input, or when referenced by `import` statements within ES module code: * Files ending in `.mjs`. diff --git a/esm/experimental_json_modules.md b/esm/experimental_json_modules.md index dd1fd884..d1a1ed0e 100644 --- a/esm/experimental_json_modules.md +++ b/esm/experimental_json_modules.md @@ -23,7 +23,7 @@ The `--experimental-json-modules` flag is needed for the module to work. ```bash -node --experimental-modules index.mjs # fails -node --experimental-modules --experimental-json-modules index.mjs # works +node index.mjs # fails +node --experimental-json-modules index.mjs # works ``` diff --git a/esm/experimental_wasm_modules.md b/esm/experimental_wasm_modules.md index 8a1db3aa..bf5c6be7 100644 --- a/esm/experimental_wasm_modules.md +++ b/esm/experimental_wasm_modules.md @@ -16,7 +16,7 @@ console.log(M); executed under: ```bash -node --experimental-modules --experimental-wasm-modules index.mjs +node --experimental-wasm-modules index.mjs ``` would provide the exports interface for the instantiation of `module.wasm`. diff --git a/esm/input_type_flag.md b/esm/input_type_flag.md index 556a327c..04f9fe1e 100644 --- a/esm/input_type_flag.md +++ b/esm/input_type_flag.md @@ -4,11 +4,9 @@ piped to `node` via `STDIN`, will be treated as ES modules when the `--input-type=module` flag is set. ```sh -node --experimental-modules --input-type=module --eval \ - "import { sep } from 'path'; console.log(sep);" +node --input-type=module --eval "import { sep } from 'path'; console.log(sep);" -echo "import { sep } from 'path'; console.log(sep);" | \ - node --experimental-modules --input-type=module +echo "import { sep } from 'path'; console.log(sep);" | node --input-type=module ``` For completeness there is also `--input-type=commonjs`, for explicitly running diff --git a/esm/package_json_type_field.md b/esm/package_json_type_field.md index a3a7da9b..0442ea64 100644 --- a/esm/package_json_type_field.md +++ b/esm/package_json_type_field.md @@ -17,7 +17,7 @@ until the root of the volume is reached. ```sh # In same folder as above package.json -node --experimental-modules my-app.js # Runs as ES module +node my-app.js # Runs as ES module ``` If the nearest parent `package.json` lacks a `"type"` field, or contains diff --git a/esm/package_scope_and_file_extensions.md b/esm/package_scope_and_file_extensions.md index 6f8ba741..f16c758f 100644 --- a/esm/package_scope_and_file_extensions.md +++ b/esm/package_scope_and_file_extensions.md @@ -7,9 +7,8 @@ project’s `node_modules` folder contains its own `package.json` file, so each project’s dependencies have their own package scopes. A `package.json` lacking a `"type"` field is treated as if it contained `"type": "commonjs"`. -The package scope applies not only to initial entry points (`node ---experimental-modules my-app.js`) but also to files referenced by `import` -statements and `import()` expressions. +The package scope applies not only to initial entry points (`node my-app.js`) +but also to files referenced by `import` statements and `import()` expressions. ```js // my-app.js, in an ES module package scope because there is a package.json diff --git a/esm/resolver_algorithm.md b/esm/resolver_algorithm.md index 0aa19a2e..5cd55c52 100644 --- a/esm/resolver_algorithm.md +++ b/esm/resolver_algorithm.md @@ -196,7 +196,7 @@ The resolver can throw the following errors: > 1. If _exports_ contains any index property keys, as defined in ECMA-262 > [6.1.7 Array Index][], throw an _Invalid Package Configuration_ error. > 1. For each property _p_ of _target_, in object insertion order as, -> 1. If _env_ contains an entry for _p_, then +> 1. If _p_ equals _"default"_ or _env_ contains an entry for _p_, then > 1. Let _targetValue_ be the value of the _p_ property in _target_. > 1. Return the result of **PACKAGE_EXPORTS_TARGET_RESOLVE**( > _packageURL_, _targetValue_, _subpath_, _env_), continuing the diff --git a/events/class_eventemitter.md b/events/class_eventemitter.md index d6bb9809..99645b5a 100644 --- a/events/class_eventemitter.md +++ b/events/class_eventemitter.md @@ -1,7 +1,7 @@ diff --git a/events/emitter_setmaxlisteners_n.md b/events/emitter_setmaxlisteners_n.md index 50bdd628..6a16b887 100644 --- a/events/emitter_setmaxlisteners_n.md +++ b/events/emitter_setmaxlisteners_n.md @@ -6,7 +6,6 @@ added: v0.3.5 默认情况下,如果为特定事件添加了超过 `10` 个监听器,则 `EventEmitter` 会打印一个警告。 这有助于发现内存泄露。 -但是,并不是所有的事件都要限制 `10` 个监听器。 `emitter.setMaxListeners()` 方法可以为指定的 `EventEmitter` 实例修改限制。 值设为 `Infinity`(或 `0`)表示不限制监听器的数量。 diff --git a/events/emitter_symbol_for_nodejs_rejection_err_eventname_args.md b/events/emitter_symbol_for_nodejs_rejection_err_eventname_args.md index d328a975..89bfba6a 100644 --- a/events/emitter_symbol_for_nodejs_rejection_err_eventname_args.md +++ b/events/emitter_symbol_for_nodejs_rejection_err_eventname_args.md @@ -1,5 +1,5 @@ > Stability: 1 - captureRejections is experimental. diff --git a/events/error_events.md b/events/error_events.md index fbf168f7..a6844a47 100644 --- a/events/error_events.md +++ b/events/error_events.md @@ -24,4 +24,13 @@ myEmitter.emit('error', new Error('错误')); // 打印: 错误信息 ``` +通过使用符号 `errorMonitor` 安装监听器,可以监视 `'error'` 事件但不消耗触发的错误。 +```js +const myEmitter = new MyEmitter(); +myEmitter.on(EventEmitter.errorMonitor, (err) => { + MyMonitoringTool.log(err); +}); +myEmitter.emit('error', new Error('错误')); +// 仍然抛出错误并使 Node.js 崩溃。 +``` diff --git a/events/eventemitter_errormonitor.md b/events/eventemitter_errormonitor.md new file mode 100644 index 00000000..30a76fe4 --- /dev/null +++ b/events/eventemitter_errormonitor.md @@ -0,0 +1,12 @@ + + +This symbol shall be used to install a listener for only monitoring `'error'` +events. Listeners installed using this symbol are called before the regular +`'error'` listeners are called. + +Installing a listener using this symbol does not change the behavior once an +`'error'` event is emitted, therefore the process will still crash if no +regular `'error'` listener is installed. + diff --git a/events/events_capturerejections.md b/events/events_capturerejections.md index c1bee9b0..82cb7183 100644 --- a/events/events_capturerejections.md +++ b/events/events_capturerejections.md @@ -1,5 +1,5 @@ > Stability: 1 - captureRejections is experimental. diff --git a/events/events_capturerejectionsymbol.md b/events/events_capturerejectionsymbol.md index 22bff5d6..d925af90 100644 --- a/events/events_capturerejectionsymbol.md +++ b/events/events_capturerejectionsymbol.md @@ -1,5 +1,5 @@ > Stability: 1 - captureRejections is experimental. diff --git a/events/events_on_emitter_eventname.md b/events/events_on_emitter_eventname.md index bcd3ac92..e33231bc 100644 --- a/events/events_on_emitter_eventname.md +++ b/events/events_on_emitter_eventname.md @@ -1,5 +1,5 @@ * `emitter` {EventEmitter} @@ -24,6 +24,7 @@ const { on, EventEmitter } = require('events'); // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } + // Unreachable here })(); ``` diff --git a/fs/availability.md b/fs/availability.md index 593b41d4..355b4e93 100644 --- a/fs/availability.md +++ b/fs/availability.md @@ -10,8 +10,8 @@ * 在 Windows 系统上,此特性取决于 [`ReadDirectoryChangesW`]。 * 在 Aix 系统上,此特性取决于 [`AHAFS`] 必须启动。 -如果底层功能由于某些原因不可用,则 `fs.watch` 将无法运行。 -例如,当使用虚拟化软件(如 Vagrant、Docker 等)时,在网络文件系统(NFS、SMB 等)或主文件系统上监视文件或目录可能是不可靠的,在某些情况下也是不可能的。 +如果底层功能由于某些原因不可用,则 `fs.watch()` 会无法运行且可能抛出异常。 +例如,当使用虚拟化软件(如 Vagrant 或 Docker)时,在网络文件系统(NFS、SMB 等)或主文件系统上监视文件或目录可能是不可靠的,在某些情况下也是不可能的。 仍然可以使用 `fs.watchFile()`,因为它使用 stat 轮询 ,但这种方法较慢且不太可靠。 diff --git a/fs/caveats.md b/fs/caveats.md index a9a1590d..acd50c26 100644 --- a/fs/caveats.md +++ b/fs/caveats.md @@ -4,4 +4,8 @@ `fs.watch` 的 API 在各个平台上并非 100% 一致,在某些情况下不可用。 仅在 macOS 和 Windows 上支持 `recursive` 选项。 +当在不支持该选项的平台上使用该选项时,则会抛出 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 异常。 + +在 Windows 上,如果监视的目录被移动或重命名,则不会触发任何事件。 +当监视的目录被删除时,则报告 `EPERM` 错误。 diff --git a/fs/class_filehandle.md b/fs/class_filehandle.md index f27947dc..ce34c3c2 100644 --- a/fs/class_filehandle.md +++ b/fs/class_filehandle.md @@ -6,7 +6,7 @@ added: v10.0.0 `FileHandle` 的实例与数字文件描述符的不同之处在于它们提供了一个面向对象的 API 来处理文件。 如果没有使用 `filehandle.close()` 方法关闭 `FileHandle`,则它可能会自动关闭文件描述符并触发进程警告,从而有助于防止内存泄漏。 -请不要在代码中依赖此行为,因为它不可靠,且你的文件可能无法关闭。 +请不要在代码中依赖此行为,因为它不可靠,且该文件可能无法关闭。 相反,应该始终显式的关闭 `FileHandles`。 Node.js 将来可能会改变这种行为。 diff --git a/fs/file_paths.md b/fs/file_paths.md index cf2647e0..f0699b89 100644 --- a/fs/file_paths.md +++ b/fs/file_paths.md @@ -45,6 +45,6 @@ fs.open(Buffer.from('/open/some/file.txt'), 'r', (err, fd) => { 在 Windows 上,Node.js 遵循每个驱动器工作目录的概念。 当使用没有反斜杠的驱动器路径时,可以观察到此行为。 -例如,`fs.readdirSync('c:\\')` 可能会返回与 `fs.readdirSync('c:')` 不同的结果。 +例如,`fs.readdirSync('C:\\')` 可能会返回与 `fs.readdirSync('C:')` 不同的结果。 有关详细信息,参阅[此 MSDN 页面][MSDN-Rel-Path]。 diff --git a/fs/file_system_flags.md b/fs/file_system_flags.md index f122d356..23836633 100644 --- a/fs/file_system_flags.md +++ b/fs/file_system_flags.md @@ -44,7 +44,7 @@ 在 Linux 上,当以追加模式打开文件时,写入无法指定位置。 内核会忽略位置参数,并始终将数据追加到文件的末尾。 -如果要修改文件而不是覆盖文件,则标志模式应为 `'r+'` 模式而不是默认的 `'w'` 模式。 +如果要修改文件而不是覆盖文件,则 `flag` 选项需要被设置为 `'r+'` 而不是默认的 `'w'`。 某些标志的行为是特定于平台的。 例如,在 macOS 和 Linux 上使用 `'a+'` 标志打开目录(参阅下面的示例)会返回一个错误。 diff --git a/fs/filehandle_read_options.md b/fs/filehandle_read_options.md new file mode 100644 index 00000000..c1e4ae5e --- /dev/null +++ b/fs/filehandle_read_options.md @@ -0,0 +1,10 @@ + +* `options` {Object} + * `buffer` {Buffer|Uint8Array} **Default:** `Buffer.alloc(16384)` + * `offset` {integer} **Default:** `0` + * `length` {integer} **Default:** `buffer.length` + * `position` {integer} **Default:** `null` +* Returns: {Promise} + diff --git a/fs/filehandle_readv_buffers_position.md b/fs/filehandle_readv_buffers_position.md new file mode 100644 index 00000000..3c18ed35 --- /dev/null +++ b/fs/filehandle_readv_buffers_position.md @@ -0,0 +1,18 @@ + + +* `buffers` {ArrayBufferView[]} +* `position` {integer} +* Returns: {Promise} + +Read from a file and write to an array of `ArrayBufferView`s + +The `Promise` is resolved with an object containing a `bytesRead` property +identifying the number of bytes read, and a `buffers` property containing +a reference to the `buffers` input. + +`position` is the offset from the beginning of the file where this data +should be read from. If `typeof position !== 'number'`, the data will be read +from the current position. + diff --git a/fs/filehandle_write_buffer_offset_length_position.md b/fs/filehandle_write_buffer_offset_length_position.md index e2d20114..77fd48d6 100644 --- a/fs/filehandle_write_buffer_offset_length_position.md +++ b/fs/filehandle_write_buffer_offset_length_position.md @@ -1,5 +1,10 @@ * `buffer` {Buffer|Uint8Array} * `offset` {integer} diff --git a/fs/filehandle_write_string_position_encoding.md b/fs/filehandle_write_string_position_encoding.md index 1e8b14ce..b769e7a1 100644 --- a/fs/filehandle_write_string_position_encoding.md +++ b/fs/filehandle_write_string_position_encoding.md @@ -1,5 +1,10 @@ * `string` {string} @@ -8,7 +13,7 @@ added: v10.0.0 * 返回: {Promise} 将 `string` 写入到文件。 -如果 `string` 不是一个字符串,则该值会被强制转换为字符串。 +如果 `string` 不是一个字符串,则会抛出异常。 `Promise` 会被解决并带上一个对象,对象包含一个 `bytesWritten` 属性(指定写入的字节数)和一个 `buffer` 属性(指向写入的 `string`)。 diff --git a/fs/filehandle_writefile_data_options.md b/fs/filehandle_writefile_data_options.md index 6c1e09ae..137ab981 100644 --- a/fs/filehandle_writefile_data_options.md +++ b/fs/filehandle_writefile_data_options.md @@ -1,5 +1,10 @@ * `data` {string|Buffer|Uint8Array} * `options` {Object|string} diff --git a/fs/fs_copyfile_src_dest_flags_callback.md b/fs/fs_copyfile_src_dest_mode_callback.md similarity index 79% rename from fs/fs_copyfile_src_dest_flags_callback.md rename to fs/fs_copyfile_src_dest_mode_callback.md index 8932cd4a..923a3d38 100644 --- a/fs/fs_copyfile_src_dest_flags_callback.md +++ b/fs/fs_copyfile_src_dest_mode_callback.md @@ -4,7 +4,7 @@ added: v8.5.0 * `src` {string|Buffer|URL} 要拷贝的源文件名。 * `dest` {string|Buffer|URL} 拷贝操作的目标文件名。 -* `flags` {number} 用于拷贝操作的修饰符。**默认值:** `0`。 +* `mode` {integer} 用于拷贝操作的修饰符。**默认值:** `0`。 * `callback` {Function} 异步地将 `src` 拷贝到 `dest`。 @@ -13,7 +13,7 @@ added: v8.5.0 Node.js 不保证拷贝操作的原子性。 如果在打开目标文件用于写入后发生错误,则 Node.js 将尝试删除目标文件。 -`flags` 是一个可选的整数,指定拷贝操作的行为。 +`mode` 是一个可选的整数,指定拷贝操作的行为。 可以创建由两个或更多个值按位或组成的掩码(比如 `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`)。 * `fs.constants.COPYFILE_EXCL` - 如果 `dest` 已存在,则拷贝操作将失败。 @@ -22,19 +22,15 @@ Node.js 不保证拷贝操作的原子性。 ```js const fs = require('fs'); +const { COPYFILE_EXCL } = fs.constants; -// 默认情况下将创建或覆盖目标文件。 -fs.copyFile('源文件.txt', '目标文件.txt', (err) => { +function callback(err) { if (err) throw err; - console.log('源文件已拷贝到目标文件'); -}); -``` - -如果第三个参数是数字,则它指定 `flags`: + console.log('源文件已拷贝到目标文'); +} -```js -const fs = require('fs'); -const { COPYFILE_EXCL } = fs.constants; +// 默认情况下将创建或覆盖目标文件。 +fs.copyFile('源文件.txt', '目标文件.txt', callback); // 通过使用 COPYFILE_EXCL,如果目标文件存在,则操作将失败。 fs.copyFile('源文件.txt', '目标文件.txt', COPYFILE_EXCL, callback); diff --git a/fs/fs_copyfilesync_src_dest_flags.md b/fs/fs_copyfilesync_src_dest_mode.md similarity index 85% rename from fs/fs_copyfilesync_src_dest_flags.md rename to fs/fs_copyfilesync_src_dest_mode.md index faa54836..8c58dabe 100644 --- a/fs/fs_copyfilesync_src_dest_flags.md +++ b/fs/fs_copyfilesync_src_dest_mode.md @@ -4,7 +4,7 @@ added: v8.5.0 * `src` {string|Buffer|URL} 要拷贝的源文件名。 * `dest` {string|Buffer|URL} 拷贝操作的目标文件名。 -* `flags` {number} 用于拷贝操作的修饰符。**默认值:** `0`。 +* `mode` {integer} 用于拷贝操作的修饰符。**默认值:** `0`。 同步地将 `src` 拷贝到 `dest`。 默认情况下,如果 `dest` 已经存在,则覆盖它。 @@ -12,7 +12,7 @@ added: v8.5.0 Node.js 不保证拷贝操作的原子性。 如果在打开目标文件用于写入后发生错误,则 Node.js 将尝试删除目标文件。 -`flags` 是一个可选的整数,指定拷贝操作的行为。 +`mode` 是一个可选的整数,指定拷贝操作的行为。 可以创建由两个或更多个值按位或组成的掩码(比如 `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`)。 * `fs.constants.COPYFILE_EXCL` - 如果 `dest` 已存在,则拷贝操作将失败。 @@ -21,17 +21,11 @@ Node.js 不保证拷贝操作的原子性。 ```js const fs = require('fs'); +const { COPYFILE_EXCL } = fs.constants; // 默认情况下将创建或覆盖目标文件。 fs.copyFileSync('源文件.txt', '目标文件.txt'); console.log('源文件已拷贝到目标文件'); -``` - -如果第三个参数是数字,则它指定 `flags`: - -```js -const fs = require('fs'); -const { COPYFILE_EXCL } = fs.constants; // 通过使用 COPYFILE_EXCL,如果目标文件存在,则操作将失败。 fs.copyFileSync('源文件.txt', '目标文件.txt', COPYFILE_EXCL); diff --git a/fs/fs_createreadstream_path_options.md b/fs/fs_createreadstream_path_options.md index abcd59fc..670903b2 100644 --- a/fs/fs_createreadstream_path_options.md +++ b/fs/fs_createreadstream_path_options.md @@ -19,6 +19,10 @@ changes: - version: v2.3.0 pr-url: https://github.com/nodejs/node/pull/1845 description: The passed `options` object can be a string now. + - version: v13.6.0 + pr-url: https://github.com/nodejs/node/pull/29083 + description: The `fs` options allow overriding the used `fs` + implementation. --> * `path` {string|Buffer|URL} @@ -32,7 +36,8 @@ changes: * `start` {integer} * `end` {integer} **默认值:** `Infinity`。 * `highWaterMark` {integer} **默认值:** `64 * 1024`。 -* 返回: {fs.ReadStream} + * `fs` {Object|null} **默认值:** `null`。 +* 返回: {fs.ReadStream} 参阅 [Readable Stream]。 与用于可读流的 16 kb 的默认的 `highWaterMark` 不同,此方法返回的流具有 64 kb 的默认的 `highWaterMark`。 @@ -52,6 +57,9 @@ changes: 这与其他 `Readable` 流的默认行为相反。 将 `emitClose` 选项设置为 `true` 可更改此行为。 +通过提供 `fs` 选项,可以重写相应的 `fs` 实现以进行 `open`、`read` 和 `close`。 +当提供 `fs` 选项时,需要重写 `open`、`read` 和 `close`。 + ```js const fs = require('fs'); // 从某个字符设备创建一个流。 diff --git a/fs/fs_createwritestream_path_options.md b/fs/fs_createwritestream_path_options.md index 5d0b7156..e47245ff 100644 --- a/fs/fs_createwritestream_path_options.md +++ b/fs/fs_createwritestream_path_options.md @@ -17,6 +17,10 @@ changes: - version: v2.3.0 pr-url: https://github.com/nodejs/node/pull/1845 description: The passed `options` object can be a string now. + - version: v13.6.0 + pr-url: https://github.com/nodejs/node/pull/29083 + description: The `fs` options allow overriding the used `fs` + implementation. --> * `path` {string|Buffer|URL} @@ -28,7 +32,8 @@ changes: * `autoClose` {boolean} **默认值:** `true`。 * `emitClose` {boolean} **默认值:** `false`。 * `start` {integer} -* 返回: {fs.WriteStream} + * `fs` {Object|null} **默认值:** `null`。 +* 返回: {fs.WriteStream} 参阅 [Writable Stream]。 `options` 可以包括 `start` 选项,允许在文件的开头之后的某个位置写入数据,允许的值在 [0, [`Number.MAX_SAFE_INTEGER`]] 的范围内。 若要修改文件而不是覆盖它,则 `flags` 模式需要为 `r+` 而不是默认的 `w` 模式。 @@ -42,6 +47,10 @@ changes: 这与其他 `Writable` 流的默认行为相反。 将 `emitClose` 选项设置为 `true` 可更改此行为。 +通过提供 `fs` 选项,可以重写相应的 `fs` 实现以进行 `open`、`write`、`writev` 和 `close`。 +不使用 `writev()` 重写 `write()` 会降低性能,因为某些优化(`_writev()`)会被禁用。 +当提供 `fs` 选项时,需要重写 `open`、`close`,以及 `write` 或 `writev` 两者之一。 + 与 [`ReadStream`] 类似,如果指定了 `fd`,则 [`WriteStream`] 将会忽略 `path` 参数并将会使用指定的文件描述符。 这意味着不会触发 `'open'` 事件。 `fd` 必须是阻塞的,非阻塞的 `fd` 应该传给 [`net.Socket`]。 diff --git a/fs/fs_mkdir_path_options_callback.md b/fs/fs_mkdir_path_options_callback.md index e22f3489..cce507de 100644 --- a/fs/fs_mkdir_path_options_callback.md +++ b/fs/fs_mkdir_path_options_callback.md @@ -1,6 +1,10 @@ diff --git a/fs/fs_opendirsync_path_options.md b/fs/fs_opendirsync_path_options.md index 29dfc33b..ebb97cbe 100644 --- a/fs/fs_opendirsync_path_options.md +++ b/fs/fs_opendirsync_path_options.md @@ -1,7 +1,7 @@ diff --git a/fs/fs_opensync_path_flags_mode.md b/fs/fs_opensync_path_flags_mode.md index a2a65575..60effb08 100644 --- a/fs/fs_opensync_path_flags_mode.md +++ b/fs/fs_opensync_path_flags_mode.md @@ -6,7 +6,7 @@ changes: description: The `flags` argument is now optional and defaults to `'r'`. - version: v9.9.0 pr-url: https://github.com/nodejs/node/pull/18801 - description: The `as` and `as+` modes are supported now. + description: The `as` and `as+` flags are supported now. - version: v7.6.0 pr-url: https://github.com/nodejs/node/pull/10739 description: The `path` parameter can be a WHATWG `URL` object using `file:` diff --git a/fs/fs_promises_api.md b/fs/fs_promises_api.md index 6cfd33c4..d13a5cb0 100644 --- a/fs/fs_promises_api.md +++ b/fs/fs_promises_api.md @@ -1,4 +1,4 @@ `fs.promises` API 提供了一组备用的异步文件系统的方法,它们返回 `Promise` 对象而不是使用回调。 -API 可通过 `require('fs').promises` 访问。 +API 可通过 `require('fs').promises` 或 `require('fs/promises')` 访问。 diff --git a/fs/fs_read_fd_buffer_offset_length_position_callback.md b/fs/fs_read_fd_buffer_offset_length_position_callback.md index 99a69a54..4874592a 100644 --- a/fs/fs_read_fd_buffer_offset_length_position_callback.md +++ b/fs/fs_read_fd_buffer_offset_length_position_callback.md @@ -25,7 +25,7 @@ changes: 从 `fd` 指定的文件中读取数据。 -`buffer` 是数据将写入的缓冲区。 +`buffer` 是数据(从 fd 读取)将写入的缓冲区。 `offset` 是 buffer 中开始写入的偏移量。 diff --git a/fs/fs_read_fd_options_callback.md b/fs/fs_read_fd_options_callback.md new file mode 100644 index 00000000..38412e6f --- /dev/null +++ b/fs/fs_read_fd_options_callback.md @@ -0,0 +1,22 @@ + +* `fd` {integer} +* `options` {Object} + * `buffer` {Buffer|TypedArray|DataView} **Default:** `Buffer.alloc(16384)` + * `offset` {integer} **Default:** `0` + * `length` {integer} **Default:** `buffer.length` + * `position` {integer} **Default:** `null` +* `callback` {Function} + * `err` {Error} + * `bytesRead` {integer} + * `buffer` {Buffer} + +Similar to the above `fs.read` function, this version takes an optional `options` object. +If no `options` object is specified, it will default with the above values. + diff --git a/fs/fs_readsync_fd_buffer_options.md b/fs/fs_readsync_fd_buffer_options.md new file mode 100644 index 00000000..e72f82d3 --- /dev/null +++ b/fs/fs_readsync_fd_buffer_options.md @@ -0,0 +1,25 @@ + + +* `fd` {integer} +* `buffer` {Buffer|TypedArray|DataView} +* `options` {Object} + * `offset` {integer} **Default:** `0` + * `length` {integer} **Default:** `buffer.length` + * `position` {integer} **Default:** `null` +* Returns: {number} + +Returns the number of `bytesRead`. + +Similar to the above `fs.readSync` function, this version takes an optional `options` object. +If no `options` object is specified, it will default with the above values. + +For detailed information, see the documentation of the asynchronous version of +this API: [`fs.read()`][]. + diff --git a/fs/fs_readv_fd_buffers_position_callback.md b/fs/fs_readv_fd_buffers_position_callback.md new file mode 100644 index 00000000..fb5d7d91 --- /dev/null +++ b/fs/fs_readv_fd_buffers_position_callback.md @@ -0,0 +1,22 @@ + + +* `fd` {integer} +* `buffers` {ArrayBufferView[]} +* `position` {integer} +* `callback` {Function} + * `err` {Error} + * `bytesRead` {integer} + * `buffers` {ArrayBufferView[]} + +Read from a file specified by `fd` and write to an array of `ArrayBufferView`s +using `readv()`. + +`position` is the offset from the beginning of the file from where data +should be read. If `typeof position !== 'number'`, the data will be read +from the current position. + +The callback will be given three arguments: `err`, `bytesRead`, and +`buffers`. `bytesRead` is how many bytes were read from the file. + diff --git a/fs/fs_readvsync_fd_buffers_position.md b/fs/fs_readvsync_fd_buffers_position.md new file mode 100644 index 00000000..d4418c96 --- /dev/null +++ b/fs/fs_readvsync_fd_buffers_position.md @@ -0,0 +1,12 @@ + + +* `fd` {integer} +* `buffers` {ArrayBufferView[]} +* `position` {integer} +* Returns: {number} The number of bytes read. + +For detailed information, see the documentation of the asynchronous version of +this API: [`fs.readv()`][]. + diff --git a/fs/fs_rmdir_path_options_callback.md b/fs/fs_rmdir_path_options_callback.md index 936c58b9..203e8437 100644 --- a/fs/fs_rmdir_path_options_callback.md +++ b/fs/fs_rmdir_path_options_callback.md @@ -1,7 +1,7 @@ diff --git a/fs/fspromises_rmdir_path_options.md b/fs/fspromises_rmdir_path_options.md index c981fbf3..72468baa 100644 --- a/fs/fspromises_rmdir_path_options.md +++ b/fs/fspromises_rmdir_path_options.md @@ -1,7 +1,7 @@ * `file` {string|Buffer|URL|FileHandle} 文件名或 `FileHandle`。 diff --git a/http/agent_freesockets.md b/http/agent_freesockets.md index 7bbed313..19021c55 100644 --- a/http/agent_freesockets.md +++ b/http/agent_freesockets.md @@ -7,3 +7,5 @@ added: v0.11.4 一个对象,其中包含当启用 `keepAlive` 时代理正在等待使用的套接字数组。 不要修改。 +`freeSockets` 列表中的 socket 会在 `'timeout' 时自动被销毁并从数组中删除。 + diff --git a/http/class_http_incomingmessage.md b/http/class_http_incomingmessage.md index f08dc512..d4b11467 100644 --- a/http/class_http_incomingmessage.md +++ b/http/class_http_incomingmessage.md @@ -1,7 +1,7 @@ diff --git a/http/http_createserver_options_requestlistener.md b/http/http_createserver_options_requestlistener.md index 7bf0058c..3e5ade5d 100644 --- a/http/http_createserver_options_requestlistener.md +++ b/http/http_createserver_options_requestlistener.md @@ -1,9 +1,12 @@ +> Stability: 0 - Deprecated. Use [`request.socket`][]. + * {stream.Duplex} -请参阅 [`request.socket`]。 +See [`request.socket`][]. diff --git a/http/request_finished.md b/http/request_finished.md index 849f0524..38d61fa1 100644 --- a/http/request_finished.md +++ b/http/request_finished.md @@ -1,13 +1,13 @@ > Stability: 0 - Deprecated. Use [`request.writableEnded`][]. * {boolean} -如果调用了 [`request.end()`],则 `request.finished` 属性将为 `true`。 -如果请求是通过 [`http.get()`] 发起的,则会自动调用 `request.end()`。 - +The `request.finished` property will be `true` if [`request.end()`][] +has been called. `request.end()` will automatically be called if the +request was initiated via [`http.get()`][]. diff --git a/http/request_reusedsocket.md b/http/request_reusedsocket.md index 20bfb6c8..3018ff49 100644 --- a/http/request_reusedsocket.md +++ b/http/request_reusedsocket.md @@ -1,6 +1,6 @@ * {boolean} Whether the request is send through a reused socket. diff --git a/http/response_connection.md b/http/response_connection.md index abd7cce5..7be9d676 100644 --- a/http/response_connection.md +++ b/http/response_connection.md @@ -1,8 +1,11 @@ +> Stability: 0 - Deprecated. Use [`response.socket`][]. + * {stream.Duplex} -参阅 [`response.socket`]。 +See [`response.socket`][]. diff --git a/http/response_cork.md b/http/response_cork.md index 23a2c363..b715f9bf 100644 --- a/http/response_cork.md +++ b/http/response_cork.md @@ -1,5 +1,5 @@ See [`writable.cork()`][]. diff --git a/http/response_finished.md b/http/response_finished.md index d05bafb7..3891100e 100644 --- a/http/response_finished.md +++ b/http/response_finished.md @@ -1,11 +1,12 @@ > Stability: 0 - Deprecated. Use [`response.writableEnded`][]. * {boolean} -如果调用了 [`response.end()`],则 `response.finished` 属性将会是 `true`。 +The `response.finished` property will be `true` if [`response.end()`][] +has been called. diff --git a/http/response_uncork.md b/http/response_uncork.md index 2e7aaa5c..c583bfa3 100644 --- a/http/response_uncork.md +++ b/http/response_uncork.md @@ -1,5 +1,5 @@ See [`writable.uncork()`][]. diff --git a/http/response_writehead_statuscode_statusmessage_headers.md b/http/response_writehead_statuscode_statusmessage_headers.md index f8997d83..a24813a4 100644 --- a/http/response_writehead_statuscode_statusmessage_headers.md +++ b/http/response_writehead_statuscode_statusmessage_headers.md @@ -53,8 +53,7 @@ const server = http.createServer((req, res) => { ``` `Content-Length` 以字节而非字符为单位。 -上面的示例可行是因为字符串 `'hello world'` 仅包含单字节字符。 -如果主体包含更高编码的字符,则应使用 `Buffer.byteLength()` 来判断给定编码中的字节数。 +使用 `Buffer.byteLength()` 来判断主体的长度(以字节为单位)。 Node.js 不检查 `Content-Length` 和已传输的主体的长度是否相等。 尝试设置包含无效字符的响应头字段名称或值将导致抛出 [`TypeError`]。 diff --git a/http/server_headerstimeout.md b/http/server_headerstimeout.md index 98cbc9e1..c59992cb 100644 --- a/http/server_headerstimeout.md +++ b/http/server_headerstimeout.md @@ -2,7 +2,7 @@ added: v11.3.0 --> -* {number} **默认值:** `40000`。 +* {number} **默认值:** `60000`。 限制解析器等待接收完整 HTTP 请求头的时间。 diff --git a/http/server_settimeout_msecs_callback.md b/http/server_settimeout_msecs_callback.md index e40c73fb..7e9bba4b 100644 --- a/http/server_settimeout_msecs_callback.md +++ b/http/server_settimeout_msecs_callback.md @@ -1,5 +1,9 @@ * `msecs` {number} **默认值:** `120000`(2 分钟)。 @@ -10,9 +14,7 @@ added: v0.9.12 如果服务器对象上有 `'timeout'` 事件监听器,则将使用超时的套接字作为参数调用它。 -默认情况下,服务器的超时值为 2 分钟,如果超时,套接字会自动销毁。 +默认情况下,服务器不会使 socket 超时。 但是,如果将回调分配给服务器的 `'timeout'` 事件,则必须显式处理超时。 -若要更改默认的超时,请使用 [`--http-server-default-timeout`] 标志。 - diff --git a/http/server_timeout.md b/http/server_timeout.md index 193576a0..5048baab 100644 --- a/http/server_timeout.md +++ b/http/server_timeout.md @@ -1,5 +1,9 @@ * {number} 超时时间(以毫秒为单位)。**默认值:** `120000`(2 分钟)。 @@ -10,5 +14,4 @@ added: v0.9.12 套接字超时逻辑在连接时设置,因此更改此值仅影响到服务器的新连接,而不影响任何现有连接。 -若要更改默认的超时,请使用 [`--http-server-default-timeout`] 标志。 diff --git a/http2/collecting_http_2_performance_metrics.md b/http2/collecting_http_2_performance_metrics.md index 2801c9bc..b50d542c 100644 --- a/http2/collecting_http_2_performance_metrics.md +++ b/http2/collecting_http_2_performance_metrics.md @@ -109,6 +109,5 @@ following additional properties: - diff --git a/http2/event_timeout_2.md b/http2/event_timeout_2.md index 79c933ed..67529e0b 100644 --- a/http2/event_timeout_2.md +++ b/http2/event_timeout_2.md @@ -1,11 +1,12 @@ The `'timeout'` event is emitted when there is no activity on the Server for a given number of milliseconds set using `http2server.setTimeout()`. -**Default:** 2 minutes. - -To change the default timeout use the [`--http-server-default-timeout`][] -flag. +**Default:** 0 (no timeout) diff --git a/http2/http2_connect_authority_options_listener.md b/http2/http2_connect_authority_options_listener.md index 068ccd30..0a151407 100644 --- a/http2/http2_connect_authority_options_listener.md +++ b/http2/http2_connect_authority_options_listener.md @@ -1,6 +1,11 @@ + +> Stability: 0 - Deprecated. Use [`request.socket`][]. + +* {net.Socket|tls.TLSSocket} + +See [`request.socket`][]. + diff --git a/http2/response_connection.md b/http2/response_connection.md index 095d02e3..43c6bff2 100644 --- a/http2/response_connection.md +++ b/http2/response_connection.md @@ -1,7 +1,10 @@ +> Stability: 0 - Deprecated. Use [`response.socket`][]. + * {net.Socket|tls.TLSSocket} See [`response.socket`][]. diff --git a/http2/response_finished.md b/http2/response_finished.md index ba2a45fd..9acd3c58 100644 --- a/http2/response_finished.md +++ b/http2/response_finished.md @@ -1,6 +1,6 @@ > Stability: 0 - Deprecated. Use [`response.writableEnded`][]. diff --git a/http2/server_settimeout_msecs_callback.md b/http2/server_settimeout_msecs_callback.md index 6cab3995..0ea6ec1e 100644 --- a/http2/server_settimeout_msecs_callback.md +++ b/http2/server_settimeout_msecs_callback.md @@ -1,8 +1,12 @@ -* `msecs` {number} **Default:** `120000` (2 minutes) +* `msecs` {number} **Default:** 0 (no timeout) * `callback` {Function} * Returns: {Http2Server} @@ -12,9 +16,6 @@ on the `Http2Server` after `msecs` milliseconds. The given callback is registered as a listener on the `'timeout'` event. -In case of no callback function were assigned, a new `ERR_INVALID_CALLBACK` +In case if `callback` is not a function, a new `ERR_INVALID_CALLBACK` error will be thrown. -To change the default timeout use the [`--http-server-default-timeout`][] -flag. - diff --git a/http2/server_settimeout_msecs_callback_1.md b/http2/server_settimeout_msecs_callback_1.md index 1761544d..4d711d1a 100644 --- a/http2/server_settimeout_msecs_callback_1.md +++ b/http2/server_settimeout_msecs_callback_1.md @@ -12,6 +12,6 @@ on the `Http2SecureServer` after `msecs` milliseconds. The given callback is registered as a listener on the `'timeout'` event. -In case of no callback function were assigned, a new `ERR_INVALID_CALLBACK` +In case if `callback` is not a function, a new `ERR_INVALID_CALLBACK` error will be thrown. diff --git a/http2/server_timeout.md b/http2/server_timeout.md new file mode 100644 index 00000000..948e7ab4 --- /dev/null +++ b/http2/server_timeout.md @@ -0,0 +1,18 @@ + + +* {number} Timeout in milliseconds. **Default:** 0 (no timeout) + +The number of milliseconds of inactivity before a socket is presumed +to have timed out. + +A value of `0` will disable the timeout behavior on incoming connections. + +The socket timeout logic is set up on connection, so changing this +value only affects new connections to the server, not any existing connections. + diff --git a/http2/server_timeout_1.md b/http2/server_timeout_1.md new file mode 100644 index 00000000..948e7ab4 --- /dev/null +++ b/http2/server_timeout_1.md @@ -0,0 +1,18 @@ + + +* {number} Timeout in milliseconds. **Default:** 0 (no timeout) + +The number of milliseconds of inactivity before a socket is presumed +to have timed out. + +A value of `0` will disable the timeout behavior on incoming connections. + +The socket timeout logic is set up on connection, so changing this +value only affects new connections to the server, not any existing connections. + diff --git a/http2/using_options_selectpadding.md b/http2/using_options_selectpadding.md deleted file mode 100644 index f2b37ce4..00000000 --- a/http2/using_options_selectpadding.md +++ /dev/null @@ -1,23 +0,0 @@ - -When `options.paddingStrategy` is equal to -`http2.constants.PADDING_STRATEGY_CALLBACK`, the HTTP/2 implementation will -consult the `options.selectPadding()` callback function, if provided, to -determine the specific amount of padding to use per `HEADERS` and `DATA` frame. - -The `options.selectPadding()` function receives two numeric arguments, -`frameLen` and `maxFrameLen` and must return a number `N` such that -`frameLen <= N <= maxFrameLen`. - -```js -const http2 = require('http2'); -const server = http2.createServer({ - paddingStrategy: http2.constants.PADDING_STRATEGY_CALLBACK, - selectPadding(frameLen, maxFrameLen) { - return maxFrameLen; - } -}); -``` - -The `options.selectPadding()` function is invoked once for *every* `HEADERS` and -`DATA` frame. This has a definite noticeable impact on performance. - diff --git a/intl/detecting_internationalization_support.md b/intl/detecting_internationalization_support.md index d66c3eae..18e73804 100644 --- a/intl/detecting_internationalization_support.md +++ b/intl/detecting_internationalization_support.md @@ -58,6 +58,5 @@ to be helpful: - diff --git a/intl/disable_all_internationalization_features_none.md b/intl/disable_all_internationalization_features_none.md index 211a5d5e..cbb29381 100644 --- a/intl/disable_all_internationalization_features_none.md +++ b/intl/disable_all_internationalization_features_none.md @@ -1,4 +1,4 @@ -If this option is chosen, most internationalization features mentioned above -will be **unavailable** in the resulting `node` binary. +If this option is chosen, ICU is disabled and most internationalization +features mentioned above will be **unavailable** in the resulting `node` binary. diff --git a/intl/embed_a_limited_set_of_icu_data_small_icu.md b/intl/embed_a_limited_set_of_icu_data_small_icu.md index 5cc58195..f286fadc 100644 --- a/intl/embed_a_limited_set_of_icu_data_small_icu.md +++ b/intl/embed_a_limited_set_of_icu_data_small_icu.md @@ -20,7 +20,5 @@ console.log(spanish.format(january)); // Should print "enero" ``` -This mode provides a good balance between features and binary size, and it is -the default behavior if no `--with-intl` flag is passed. The official binaries -are also built in this mode. +This mode provides a balance between features and binary size. diff --git a/intl/embed_the_entire_icu_full_icu.md b/intl/embed_the_entire_icu_full_icu.md index c686633d..ce6f0af8 100644 --- a/intl/embed_the_entire_icu_full_icu.md +++ b/intl/embed_the_entire_icu_full_icu.md @@ -1,6 +1,7 @@ This option makes the resulting binary link against ICU statically and include a full set of ICU data. A binary created this way has no further external -dependencies and supports all locales, but might be rather large. See -[BUILDING.md][BUILDING.md#full-icu] on how to compile a binary using this mode. +dependencies and supports all locales, but might be rather large. This is +the default behavior if no `--with-intl` flag is passed. The official binaries +are also built in this mode. diff --git a/intl/internationalization_support.md b/intl/internationalization_support.md index edf669b0..614e290f 100644 --- a/intl/internationalization_support.md +++ b/intl/internationalization_support.md @@ -22,10 +22,8 @@ programs. Some of them are: * [`RegExp` Unicode Property Escapes][] Node.js (and its underlying V8 engine) uses [ICU][] to implement these features -in native C/C++ code. However, some of them require a very large ICU data file -in order to support all locales of the world. Because it is expected that most -Node.js users will make use of only a small portion of ICU functionality, only -a subset of the full ICU data set is provided by Node.js by default. Several -options are provided for customizing and expanding the ICU data set either when +in native C/C++ code. The full ICU data set is provided by Node.js by default. +However, due to the size of the ICU data file, several +options are provided for customizing the ICU data set either when building or running Node.js. diff --git a/intl/options_for_building_node_js.md b/intl/options_for_building_node_js.md index d946220f..4a0d0183 100644 --- a/intl/options_for_building_node_js.md +++ b/intl/options_for_building_node_js.md @@ -5,8 +5,8 @@ in [BUILDING.md][]. * `--with-intl=none`/`--without-intl` * `--with-intl=system-icu` -* `--with-intl=small-icu` (default) -* `--with-intl=full-icu` +* `--with-intl=small-icu` +* `--with-intl=full-icu` (default) An overview of available Node.js and JavaScript features for each `configure` option: diff --git a/modules/all_together.md b/modules/all_together.md index 3bfc3ed3..ffa22990 100644 --- a/modules/all_together.md +++ b/modules/all_together.md @@ -21,7 +21,7 @@ require(X) from module at path Y 6. THROW "not found" LOAD_AS_FILE(X) -1. If X is a file, load X as JavaScript text. STOP +1. If X is a file, load X as its file extension format. STOP 2. If X.js is a file, load X.js as JavaScript text. STOP 3. If X.json is a file, parse X.json to a JavaScript Object. STOP 4. If X.node is a file, load X.node as binary addon. STOP @@ -45,8 +45,9 @@ LOAD_AS_DIRECTORY(X) LOAD_NODE_MODULES(X, START) 1. let DIRS = NODE_MODULES_PATHS(START) 2. for each DIR in DIRS: - a. LOAD_AS_FILE(DIR/X) - b. LOAD_AS_DIRECTORY(DIR/X) + a. LOAD_PACKAGE_EXPORTS(DIR, X) + b. LOAD_AS_FILE(DIR/X) + c. LOAD_AS_DIRECTORY(DIR/X) NODE_MODULES_PATHS(START) 1. let PARTS = path split(START) @@ -64,45 +65,32 @@ LOAD_SELF_REFERENCE(X, START) 2. If no scope was found, return. 3. If the `package.json` has no "exports", return. 4. If the name in `package.json` isn't a prefix of X, throw "not found". -5. Otherwise, resolve the remainder of X relative to this package as if it - was loaded via `LOAD_NODE_MODULES` with a name in `package.json`. -``` - -Node.js 允许通过 `LOAD_NODE_MODULES` 加载的包显式地声明要导入的文件路径以及如何解析它们。 -这扩展了使用 `main` 字段已经拥有的控件包。 - -启用此功能后,`LOAD_NODE_MODULES` 将更改为: - - -```txt -LOAD_NODE_MODULES(X, START) -1. let DIRS = NODE_MODULES_PATHS(START) -2. for each DIR in DIRS: - a. let FILE_PATH = RESOLVE_BARE_SPECIFIER(DIR, X) - b. LOAD_AS_FILE(FILE_PATH) - c. LOAD_AS_DIRECTORY(FILE_PATH) +5. Otherwise, load the remainder of X relative to this package as if it + was loaded via `LOAD_NODE_MODULES` with a name in `package.json`. -RESOLVE_BARE_SPECIFIER(DIR, X) +LOAD_PACKAGE_EXPORTS(DIR, X) 1. Try to interpret X as a combination of name and subpath where the name may have a @scope/ prefix and the subpath begins with a slash (`/`). -2. If X matches this pattern and DIR/name/package.json is a file: - a. Parse DIR/name/package.json, and look for "exports" field. - b. If "exports" is null or undefined, GOTO 3. - c. If "exports" is an object with some keys starting with "." and some keys - not starting with ".", throw "invalid config". - d. If "exports" is a string, or object with no keys starting with ".", treat - it as having that value as its "." object property. - e. If subpath is "." and "exports" does not have a "." entry, GOTO 3. - f. Find the longest key in "exports" that the subpath starts with. - g. If no such key can be found, throw "not found". - h. let RESOLVED_URL = - PACKAGE_EXPORTS_TARGET_RESOLVE(pathToFileURL(DIR/name), exports[key], - subpath.slice(key.length), ["node", "require"]), as defined in the ESM - resolver. - i. return fileURLToPath(RESOLVED_URL) -3. return DIR/X +2. If X does not match this pattern or DIR/name/package.json is not a file, + return. +3. Parse DIR/name/package.json, and look for "exports" field. +4. If "exports" is null or undefined, return. +5. If "exports" is an object with some keys starting with "." and some keys + not starting with ".", throw "invalid config". +6. If "exports" is a string, or object with no keys starting with ".", treat + it as having that value as its "." object property. +7. If subpath is "." and "exports" does not have a "." entry, return. +8. Find the longest key in "exports" that the subpath starts with. +9. If no such key can be found, throw "not found". +10. let RESOLVED = + fileURLToPath(PACKAGE_EXPORTS_TARGET_RESOLVE(pathToFileURL(DIR/name), + exports[key], subpath.slice(key.length), ["node", "require"])), as defined + in the ESM resolver. +11. If key ends with "/": + a. LOAD_AS_FILE(RESOLVED) + b. LOAD_AS_DIRECTORY(RESOLVED) +12. Otherwise + a. If RESOLVED is a file, load it as its file extension format. STOP +13. Throw "not found" ``` -只有当加载上面定义的包名时才会遵守 `"exports"`。 -嵌套目录和包中的任何 `"exports"` 值必须由负责名称的 `package.json` 声明。 - diff --git a/modules/class_module_sourcemap.md b/modules/class_module_sourcemap.md new file mode 100644 index 00000000..7d78ee53 --- /dev/null +++ b/modules/class_module_sourcemap.md @@ -0,0 +1,4 @@ + + diff --git a/modules/module_findsourcemap_path_error.md b/modules/module_findsourcemap_path_error.md new file mode 100644 index 00000000..3162ccda --- /dev/null +++ b/modules/module_findsourcemap_path_error.md @@ -0,0 +1,17 @@ + + +* `path` {string} +* `error` {Error} +* Returns: {module.SourceMap} + +`path` is the resolved path for the file for which a corresponding source map +should be fetched. + +The `error` instance should be passed as the second parameter to `findSourceMap` +in exceptional flows, e.g., when an overridden +[`Error.prepareStackTrace(error, trace)`][] is invoked. Modules are not added to +the module cache until they are successfully loaded, in these cases source maps +will be associated with the `error` instance along with the `path`. + diff --git a/modules/module_syncbuiltinesmexports.md b/modules/module_syncbuiltinesmexports.md index 904f8d1e..6432a88b 100644 --- a/modules/module_syncbuiltinesmexports.md +++ b/modules/module_syncbuiltinesmexports.md @@ -27,16 +27,3 @@ import('fs').then((esmFS) => { }); ``` - - - - - - - - - - - - - diff --git a/modules/new_sourcemap_payload.md b/modules/new_sourcemap_payload.md new file mode 100644 index 00000000..021b278b --- /dev/null +++ b/modules/new_sourcemap_payload.md @@ -0,0 +1,15 @@ + +* `payload` {Object} + +Creates a new `sourceMap` instance. + +`payload` is an object with keys matching the [Source Map V3 format][]: + +* `file`: {string} +* `version`: {number} +* `sources`: {string[]} +* `sourcesContent`: {string[]} +* `names`: {string[]} +* `mappings`: {string} +* `sourceRoot`: {string} + diff --git a/modules/require_resolve_request_options.md b/modules/require_resolve_request_options.md index 04e4a3a0..9e7852ac 100644 --- a/modules/require_resolve_request_options.md +++ b/modules/require_resolve_request_options.md @@ -15,3 +15,5 @@ changes: 使用内部的 `require()` 机制查询模块的位置,此操作只返回解析后的文件名,不会加载该模块。 +如果找不到模块,则会抛出 `MODULE_NOT_FOUND` 错误。 + diff --git a/modules/source_map_v3_support.md b/modules/source_map_v3_support.md new file mode 100644 index 00000000..48c73965 --- /dev/null +++ b/modules/source_map_v3_support.md @@ -0,0 +1,18 @@ + + +> Stability: 1 - Experimental + +Helpers for for interacting with the source map cache. This cache is +populated when source map parsing is enabled and +[source map include directives][] are found in a modules' footer. + +To enable source map parsing, Node.js must be run with the flag +[`--enable-source-maps`][], or with code coverage enabled by setting +[`NODE_V8_COVERAGE=dir`][]. + +```js +const { findSourceMap, SourceMap } = require('module'); +``` + diff --git a/modules/sourcemap_findentry_linenumber_columnnumber.md b/modules/sourcemap_findentry_linenumber_columnnumber.md new file mode 100644 index 00000000..0f8d08c7 --- /dev/null +++ b/modules/sourcemap_findentry_linenumber_columnnumber.md @@ -0,0 +1,34 @@ + +* `lineNumber` {number} +* `columnNumber` {number} +* Returns: {Object} + +Given a line number and column number in the generated source file, returns +an object representing the position in the original file. The object returned +consists of the following keys: + +* generatedLine: {number} +* generatedColumn: {number} +* originalSource: {string} +* originalLine: {number} +* originalColumn: {number} + + + + + + + + + + + + + + + + + + + + diff --git a/modules/sourcemap_payload.md b/modules/sourcemap_payload.md new file mode 100644 index 00000000..dffd0b6d --- /dev/null +++ b/modules/sourcemap_payload.md @@ -0,0 +1,5 @@ + +* Returns: {Object} + +Getter for the payload used to construct the [`SourceMap`][] instance. + diff --git a/n-api/exceptions.md b/n-api/exceptions.md index ab516313..daebfa00 100644 --- a/n-api/exceptions.md +++ b/n-api/exceptions.md @@ -1,8 +1,7 @@ Any N-API function call may result in a pending JavaScript exception. This is -obviously the case for any function that may cause the execution of -JavaScript, but N-API specifies that an exception may be pending -on return from any of the API functions. +the case for any of the API functions, even those that may not cause the +execution of JavaScript. If the `napi_status` returned by a function is `napi_ok` then no exception is pending and no additional action is required. If the @@ -62,7 +61,7 @@ SemVer applying. In order to support this model with N-API, both in internal functionality and for module specific functionality (as its good practice), the `throw_` and `create_` functions take an optional code parameter which is the string for the code -to be added to the error object. If the optional parameter is NULL +to be added to the error object. If the optional parameter is `NULL` then no code will be associated with the error. If a code is provided, the name associated with the error is also updated to be: diff --git a/n-api/module_registration.md b/n-api/module_registration.md index 9dbce9f7..b93c268e 100644 --- a/n-api/module_registration.md +++ b/n-api/module_registration.md @@ -15,7 +15,7 @@ napi_value Init(napi_env env, napi_value exports); The return value from `Init` is treated as the `exports` object for the module. The `Init` method is passed an empty object via the `exports` parameter as a -convenience. If `Init` returns NULL, the parameter passed as `exports` is +convenience. If `Init` returns `NULL`, the parameter passed as `exports` is exported by the module. N-API modules cannot modify the `module` object but can specify anything as the `exports` property of the module. diff --git a/n-api/n_api_version_matrix.md b/n-api/n_api_version_matrix.md index 77047dfd..0596e5d3 100644 --- a/n-api/n_api_version_matrix.md +++ b/n-api/n_api_version_matrix.md @@ -10,10 +10,10 @@ listed as supporting a later version. | v6.x | | | v6.14.2* | | | | v8.x | v8.0.0* | v8.10.0* | v8.11.2 | v8.16.0 | | | v9.x | v9.0.0* | v9.3.0* | v9.11.0* | | | -| v10.x | | | v10.0.0 | | | -| v11.x | | | v11.0.0 | v11.8.0 | | -| v12.x | | | | v12.0.0 | v12.11.0 | -| v13.x | | | | | | +| v10.x | v10.0.0 | v10.0.0 | v10.0.0 | v10.16.0 | v10.17.0 | +| v11.x | v11.0.0 | v11.0.0 | v11.0.0 | v11.8.0 | | +| v12.x | v12.0.0 | v12.0.0 | v12.0.0 | v12.0.0 | v12.11.0 | +| v13.x | v13.0.0 | v13.0.0 | v13.0.0 | v13.0.0 | v13.0.0 | \* Indicates that the N-API version was released as experimental diff --git a/n-api/napi_create_bigint_int64.md b/n-api/napi_create_bigint_int64.md index a0310c93..476ca4e9 100644 --- a/n-api/napi_create_bigint_int64.md +++ b/n-api/napi_create_bigint_int64.md @@ -1,9 +1,8 @@ -> Stability: 1 - Experimental - ```C napi_status napi_create_bigint_int64(napi_env env, int64_t value, diff --git a/n-api/napi_create_bigint_uint64.md b/n-api/napi_create_bigint_uint64.md index 8bbcd84c..6eeec674 100644 --- a/n-api/napi_create_bigint_uint64.md +++ b/n-api/napi_create_bigint_uint64.md @@ -1,9 +1,8 @@ -> Stability: 1 - Experimental - ```C napi_status napi_create_bigint_uint64(napi_env env, uint64_t value, diff --git a/n-api/napi_create_bigint_words.md b/n-api/napi_create_bigint_words.md index 7c7f1a81..f1088a65 100644 --- a/n-api/napi_create_bigint_words.md +++ b/n-api/napi_create_bigint_words.md @@ -1,9 +1,8 @@ -> Stability: 1 - Experimental - ```C napi_status napi_create_bigint_words(napi_env env, int sign_bit, diff --git a/n-api/napi_detach_arraybuffer.md b/n-api/napi_detach_arraybuffer.md index d88dcca1..8e987550 100644 --- a/n-api/napi_detach_arraybuffer.md +++ b/n-api/napi_detach_arraybuffer.md @@ -1,5 +1,5 @@ > Stability: 1 - Experimental diff --git a/n-api/napi_get_all_property_names.md b/n-api/napi_get_all_property_names.md new file mode 100644 index 00000000..2d9611e7 --- /dev/null +++ b/n-api/napi_get_all_property_names.md @@ -0,0 +1,29 @@ + + +```C +napi_get_all_property_names(napi_env env, + napi_value object, + napi_key_collection_mode key_mode, + napi_key_filter key_filter, + napi_key_conversion key_conversion, + napi_value* result); +``` + +* `[in] env`: The environment that the N-API call is invoked under. +* `[in] object`: The object from which to retrieve the properties. +* `[in] key_mode`: Whether to retrieve prototype properties as well. +* `[in] key_filter`: Which properties to retrieve +(enumerable/readable/writable). +* `[in] key_conversion`: Whether to convert numbered property keys to strings. +* `[out] result`: A `napi_value` representing an array of JavaScript values +that represent the property names of the object. [`napi_get_array_length`][] and +[`napi_get_element`][] can be used to iterate over `result`. + +Returns `napi_ok` if the API succeeded. + +This API returns an array containing the names of the available properties +of this object. + diff --git a/n-api/napi_get_and_clear_last_exception.md b/n-api/napi_get_and_clear_last_exception.md index 59888929..213c1274 100644 --- a/n-api/napi_get_and_clear_last_exception.md +++ b/n-api/napi_get_and_clear_last_exception.md @@ -9,7 +9,7 @@ napi_status napi_get_and_clear_last_exception(napi_env env, ``` * `[in] env`: The environment that the API is invoked under. -* `[out] result`: The exception if one is pending, NULL otherwise. +* `[out] result`: The exception if one is pending, `NULL` otherwise. Returns `napi_ok` if the API succeeded. diff --git a/n-api/napi_get_arraybuffer_info.md b/n-api/napi_get_arraybuffer_info.md index f5988b13..26c93530 100644 --- a/n-api/napi_get_arraybuffer_info.md +++ b/n-api/napi_get_arraybuffer_info.md @@ -12,7 +12,8 @@ napi_status napi_get_arraybuffer_info(napi_env env, * `[in] env`: The environment that the API is invoked under. * `[in] arraybuffer`: `napi_value` representing the `ArrayBuffer` being queried. -* `[out] data`: The underlying data buffer of the `ArrayBuffer`. +* `[out] data`: The underlying data buffer of the `ArrayBuffer`. If byte_length + is `0`, this may be `NULL` or any other pointer value. * `[out] byte_length`: Length in bytes of the underlying data buffer. Returns `napi_ok` if the API succeeded. diff --git a/n-api/napi_get_buffer_info.md b/n-api/napi_get_buffer_info.md index 5ed01073..d58f1903 100644 --- a/n-api/napi_get_buffer_info.md +++ b/n-api/napi_get_buffer_info.md @@ -13,6 +13,7 @@ napi_status napi_get_buffer_info(napi_env env, * `[in] env`: The environment that the API is invoked under. * `[in] value`: `napi_value` representing the `node::Buffer` being queried. * `[out] data`: The underlying data buffer of the `node::Buffer`. + If length is `0`, this may be `NULL` or any other pointer value. * `[out] length`: Length in bytes of the underlying data buffer. Returns `napi_ok` if the API succeeded. diff --git a/n-api/napi_get_dataview_info.md b/n-api/napi_get_dataview_info.md index 70d6fe1f..1d076565 100644 --- a/n-api/napi_get_dataview_info.md +++ b/n-api/napi_get_dataview_info.md @@ -17,6 +17,7 @@ napi_status napi_get_dataview_info(napi_env env, properties to query. * `[out] byte_length`: `Number` of bytes in the `DataView`. * `[out] data`: The data buffer underlying the `DataView`. + If byte_length is `0`, this may be `NULL` or any other pointer value. * `[out] arraybuffer`: `ArrayBuffer` underlying the `DataView`. * `[out] byte_offset`: The byte offset within the data buffer from which to start projecting the `DataView`. diff --git a/n-api/napi_get_instance_data.md b/n-api/napi_get_instance_data.md index 7f6dfa3b..60c29af9 100644 --- a/n-api/napi_get_instance_data.md +++ b/n-api/napi_get_instance_data.md @@ -1,5 +1,6 @@ ```C diff --git a/n-api/napi_get_reference_value.md b/n-api/napi_get_reference_value.md index 85fe1c8e..66f098de 100644 --- a/n-api/napi_get_reference_value.md +++ b/n-api/napi_get_reference_value.md @@ -21,5 +21,5 @@ Returns `napi_ok` if the API succeeded. If still valid, this API returns the `napi_value` representing the JavaScript `Object` associated with the `napi_ref`. Otherwise, result -will be NULL. +will be `NULL`. diff --git a/n-api/napi_get_typedarray_info.md b/n-api/napi_get_typedarray_info.md index 05fdae05..77fe110d 100644 --- a/n-api/napi_get_typedarray_info.md +++ b/n-api/napi_get_typedarray_info.md @@ -20,7 +20,8 @@ napi_status napi_get_typedarray_info(napi_env env, * `[out] length`: The number of elements in the `TypedArray`. * `[out] data`: The data buffer underlying the `TypedArray` adjusted by the `byte_offset` value so that it points to the first element in the - `TypedArray`. + `TypedArray`. If the length of the array is `0`, this may be `NULL` or + any other pointer value. * `[out] arraybuffer`: The `ArrayBuffer` underlying the `TypedArray`. * `[out] byte_offset`: The byte offset within the underlying native array at which the first element of the arrays is located. The value for the data diff --git a/n-api/napi_get_value_bigint_int64.md b/n-api/napi_get_value_bigint_int64.md index f1fe203a..287597d6 100644 --- a/n-api/napi_get_value_bigint_int64.md +++ b/n-api/napi_get_value_bigint_int64.md @@ -1,9 +1,8 @@ -> Stability: 1 - Experimental - ```C napi_status napi_get_value_bigint_int64(napi_env env, napi_value value, diff --git a/n-api/napi_get_value_bigint_uint64.md b/n-api/napi_get_value_bigint_uint64.md index 6aa71e8f..ca7b3d30 100644 --- a/n-api/napi_get_value_bigint_uint64.md +++ b/n-api/napi_get_value_bigint_uint64.md @@ -1,9 +1,8 @@ -> Stability: 1 - Experimental - ```C napi_status napi_get_value_bigint_uint64(napi_env env, napi_value value, diff --git a/n-api/napi_get_value_bigint_words.md b/n-api/napi_get_value_bigint_words.md index 34fd7f12..ca3ffb28 100644 --- a/n-api/napi_get_value_bigint_words.md +++ b/n-api/napi_get_value_bigint_words.md @@ -1,9 +1,8 @@ -> Stability: 1 - Experimental - ```C napi_status napi_get_value_bigint_words(napi_env env, napi_value value, diff --git a/n-api/napi_get_value_string_latin1.md b/n-api/napi_get_value_string_latin1.md index 56990451..f74c61d0 100644 --- a/n-api/napi_get_value_string_latin1.md +++ b/n-api/napi_get_value_string_latin1.md @@ -13,7 +13,7 @@ napi_status napi_get_value_string_latin1(napi_env env, * `[in] env`: The environment that the API is invoked under. * `[in] value`: `napi_value` representing JavaScript string. -* `[in] buf`: Buffer to write the ISO-8859-1-encoded string into. If NULL is +* `[in] buf`: Buffer to write the ISO-8859-1-encoded string into. If `NULL` is passed in, the length of the string (in bytes) is returned. * `[in] bufsize`: Size of the destination buffer. When this value is insufficient, the returned string will be truncated. diff --git a/n-api/napi_get_value_string_utf16.md b/n-api/napi_get_value_string_utf16.md index 47b353a3..c102f5a2 100644 --- a/n-api/napi_get_value_string_utf16.md +++ b/n-api/napi_get_value_string_utf16.md @@ -13,7 +13,7 @@ napi_status napi_get_value_string_utf16(napi_env env, * `[in] env`: The environment that the API is invoked under. * `[in] value`: `napi_value` representing JavaScript string. -* `[in] buf`: Buffer to write the UTF16-LE-encoded string into. If NULL is +* `[in] buf`: Buffer to write the UTF16-LE-encoded string into. If `NULL` is passed in, the length of the string (in 2-byte code units) is returned. * `[in] bufsize`: Size of the destination buffer. When this value is insufficient, the returned string will be truncated. diff --git a/n-api/napi_get_value_string_utf8.md b/n-api/napi_get_value_string_utf8.md index 6df7f8db..6faf83af 100644 --- a/n-api/napi_get_value_string_utf8.md +++ b/n-api/napi_get_value_string_utf8.md @@ -13,7 +13,7 @@ napi_status napi_get_value_string_utf8(napi_env env, * `[in] env`: The environment that the API is invoked under. * `[in] value`: `napi_value` representing JavaScript string. -* `[in] buf`: Buffer to write the UTF8-encoded string into. If NULL is passed +* `[in] buf`: Buffer to write the UTF8-encoded string into. If `NULL` is passed in, the length of the string (in bytes) is returned. * `[in] bufsize`: Size of the destination buffer. When this value is insufficient, the returned string will be truncated. diff --git a/n-api/napi_is_detached_arraybuffer.md b/n-api/napi_is_detached_arraybuffer.md index f591993b..bdbe7a63 100644 --- a/n-api/napi_is_detached_arraybuffer.md +++ b/n-api/napi_is_detached_arraybuffer.md @@ -1,5 +1,5 @@ > Stability: 1 - Experimental diff --git a/n-api/napi_key_collection_mode.md b/n-api/napi_key_collection_mode.md new file mode 100644 index 00000000..5523b9cc --- /dev/null +++ b/n-api/napi_key_collection_mode.md @@ -0,0 +1,20 @@ + + +```C +typedef enum { + napi_key_include_prototypes, + napi_key_own_only +} napi_key_collection_mode; +``` + +Describes the `Keys/Properties` filter enums: + +`napi_key_collection_mode` limits the range of collected properties. + +`napi_key_own_only` limits the collected properties to the given +object only. `napi_key_include_prototypes` will include all keys +of the objects's prototype chain as well. + diff --git a/n-api/napi_key_conversion.md b/n-api/napi_key_conversion.md new file mode 100644 index 00000000..59a60ddd --- /dev/null +++ b/n-api/napi_key_conversion.md @@ -0,0 +1,16 @@ + + +```C +typedef enum { + napi_key_keep_numbers, + napi_key_numbers_to_strings +} napi_key_conversion; +``` + +`napi_key_numbers_to_strings` will convert integer indices to +strings. `napi_key_keep_numbers` will return numbers for integer +indices. + diff --git a/n-api/napi_key_filter.md b/n-api/napi_key_filter.md new file mode 100644 index 00000000..8e8003ae --- /dev/null +++ b/n-api/napi_key_filter.md @@ -0,0 +1,18 @@ + + +```C +typedef enum { + napi_key_all_properties = 0, + napi_key_writable = 1, + napi_key_enumerable = 1 << 1, + napi_key_configurable = 1 << 2, + napi_key_skip_strings = 1 << 3, + napi_key_skip_symbols = 1 << 4 +} napi_key_filter; +``` + +Property filter bits. They can be or'ed to build a composite filter. + diff --git a/n-api/napi_set_instance_data.md b/n-api/napi_set_instance_data.md index 98562c44..7ccea52a 100644 --- a/n-api/napi_set_instance_data.md +++ b/n-api/napi_set_instance_data.md @@ -1,5 +1,6 @@ ```C diff --git a/n-api/references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method.md b/n-api/references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method.md index 8d87aea7..cc64dd2f 100644 --- a/n-api/references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method.md +++ b/n-api/references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method.md @@ -22,7 +22,7 @@ then be modified through [`napi_reference_ref`][] and [`napi_reference_unref`][]. If an object is collected while the count for a reference is 0, all subsequent calls to get the object associated with the reference [`napi_get_reference_value`][] -will return NULL for the returned `napi_value`. An attempt to call +will return `NULL` for the returned `napi_value`. An attempt to call [`napi_reference_ref`][] for a reference whose object has been collected will result in an error. diff --git a/net/net_createconnection_options_connectlistener.md b/net/net_createconnection_options_connectlistener.md index 62e5dffd..02437649 100644 --- a/net/net_createconnection_options_connectlistener.md +++ b/net/net_createconnection_options_connectlistener.md @@ -30,7 +30,7 @@ client.on('end', () => { }); ``` -如果要连接到 `/tmp/echo.sock`,第二行只需要改为: +如果要连接到 `/tmp/echo.sock`: ```js const client = net.createConnection({ path: '/tmp/echo.sock' }); diff --git a/net/net_createconnection_port_host_connectlistener.md b/net/net_createconnection_port_host_connectlistener.md index a49cf033..16cf8ff4 100644 --- a/net/net_createconnection_port_host_connectlistener.md +++ b/net/net_createconnection_port_host_connectlistener.md @@ -2,11 +2,11 @@ added: v0.1.90 --> -* `port` {number} 套接字应该连接的端口号。会传给[`socket.connect(port[, host][, connectListener])`][`socket.connect(port, host)`]。 -* `host` {string} 套接字应该连接的主机名。会传给[`socket.connect(port[, host][, connectListener])`][`socket.connect(port, host)`]。**默认值:** `'localhost'`。 -* `connectListener` {Function} [`net.createConnection()`][] 的常见参数,在初始化套接字时对`'connect'` 事件的单次监听器,会传给 [`socket.connect(port[, host][, connectListener])`][`socket.connect(port, host)`]。 +* `port` {number} 套接字应该连接的端口号。会传给[`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]。 +* `host` {string} 套接字应该连接的主机名。会传给[`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]。**默认值:** `'localhost'`。 +* `connectListener` {Function} [`net.createConnection()`][] 的常见参数,在初始化套接字时对`'connect'` 事件的单次监听器,会传给 [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]。 * 返回: {net.Socket} 用于开启连接的新创建的套接字。 初始化一个 TCP 连接。 -这个函数用默认配置创建一个新的 [`net.Socket`],然后 [`socket.connect(port[, host][, connectListener])`][`socket.connect(port, host)`] 初始化一个连接,并返回开启连接的那个 `net.Socket`。 +这个函数用默认配置创建一个新的 [`net.Socket`],然后 [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`] 初始化一个连接,并返回开启连接的那个 `net.Socket`。 diff --git a/net/net_createserver_options_connectionlistener.md b/net/net_createserver_options_connectionlistener.md index 9e9f9e53..2e2d1fed 100644 --- a/net/net_createserver_options_connectionlistener.md +++ b/net/net_createserver_options_connectionlistener.md @@ -47,7 +47,7 @@ server.listen(8124, () => { $ telnet localhost 8124 ``` -要想在 `/tmp/echo.sock` 上监听,则最后三行需改为: +要想在 `/tmp/echo.sock` 上监听: ```js server.listen('/tmp/echo.sock', () => { diff --git a/net/server_address.md b/net/server_address.md index b9b9df82..bd0dee61 100644 --- a/net/server_address.md +++ b/net/server_address.md @@ -2,7 +2,7 @@ added: v0.1.90 --> -* 返回: {Object|string} +* 返回: {Object|string|null} 如果在 IP socket 上监听,则返回操作系统报告的绑定的 `address`、地址 `family` 名称、以及服务器 `port`(用于查找在获取操作系统分配的地址时分配的端口):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`。 @@ -22,5 +22,5 @@ server.listen(() => { }); ``` -不要在 `'listening'` 事件触发之前调用 `server.address()`。 +在 `'listening'` 事件被触发之前、或在调用 `server.close()` 之后,`server.address()` 返回 `null`。 diff --git a/net/socket_connect.md b/net/socket_connect.md index aabdccee..0154bb19 100644 --- a/net/socket_connect.md +++ b/net/socket_connect.md @@ -2,9 +2,9 @@ 可能的签名: -* [socket.connect(options[, connectListener])][`socket.connect(options)`] -* [socket.connect(path[, connectListener])][`socket.connect(path)`] 用于 [IPC][] 连接。 -* [socket.connect(port[, host][, connectListener])][`socket.connect(port, host)`] 用于 TCP 连接。 +* [`socket.connect(options[, connectListener])`][`socket.connect(options)`] +* [`socket.connect(path[, connectListener])`][`socket.connect(path)`] 用于 [IPC][] 连接。 +* [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`] 用于 TCP 连接。 * 返回: {net.Socket} socket 自身。 该方法是异步的。当连接建立了的时候,[`'connect'`][] 事件将会被触发。如果连接过程中有问题,[`'error'`][] 事件将会代替 [`'connect'`][] 事件被触发,并将错误信息传递给 [`'error'`][] 监听器。 diff --git a/net/socket_destroy_error.md b/net/socket_destroy_error.md new file mode 100644 index 00000000..cdf44a4c --- /dev/null +++ b/net/socket_destroy_error.md @@ -0,0 +1,11 @@ + + +* `error` {Object} +* 返回: {net.Socket} + +确保在此 socket 上不再有 I/O 活动。 +销毁流并关闭连接。 + +有关更多详细信息,参阅 [`writable.destroy()`]。 diff --git a/net/socket_destroy_exception.md b/net/socket_destroy_exception.md deleted file mode 100644 index 912c754f..00000000 --- a/net/socket_destroy_exception.md +++ /dev/null @@ -1,10 +0,0 @@ - - -* `exception` {Object} -* 返回: {net.Socket} - -确保在该 socket 上不再有 I/O 活动。仅在出现错误的时候才需要(如解析错误等)。 - -如果制定了 `exception`,则将会触发一个 [`'error'`][] 事件,任何监听器都将接收到 `exception` 作为一个参数。 diff --git a/net/socket_destroyed.md b/net/socket_destroyed.md index 993cadbd..ca842fd2 100644 --- a/net/socket_destroyed.md +++ b/net/socket_destroyed.md @@ -1,2 +1,4 @@ * {boolean} 指示连接是否已经被销毁。一旦连接被销毁就不能再使用它传输任何数据。 + +有关更多详细信息,参阅 [`writable.destroyed`]。 diff --git a/net/socket_end_data_encoding_callback.md b/net/socket_end_data_encoding_callback.md index 4a93190f..22858ed0 100644 --- a/net/socket_end_data_encoding_callback.md +++ b/net/socket_end_data_encoding_callback.md @@ -13,3 +13,5 @@ added: v0.1.90 如果指定了 `data`,则相当于调用 `socket.write(data, encoding)` 之后再调用 [`socket.end()`]。 +有关更多详细信息,参阅 [`writable.end()`]。 + diff --git a/os/os_version.md b/os/os_version.md new file mode 100644 index 00000000..2b6e336f --- /dev/null +++ b/os/os_version.md @@ -0,0 +1,13 @@ + + +* Returns {string} + +Returns a string identifying the kernel version. + +On POSIX systems, the operating system release is determined by calling +[uname(3)][]. On Windows, `RtlGetVersion()` is used, and if it is not available, +`GetVersionExW()` will be used. See +https://en.wikipedia.org/wiki/Uname#Examples for more information. + diff --git a/path/path_extname_path.md b/path/path_extname_path.md index e355f593..8e4cc4ca 100644 --- a/path/path_extname_path.md +++ b/path/path_extname_path.md @@ -3,7 +3,7 @@ added: v0.1.25 changes: - version: v6.0.0 pr-url: https://github.com/nodejs/node/pull/5348 - description: Passing a non-string as the `path` argument will throw now. + description: 现在将非字符串作为 `path` 参数传入会抛出异常。 --> * `path` {string} diff --git a/perf_hooks/performance_measure_name_startmark_endmark.md b/perf_hooks/performance_measure_name_startmark_endmark.md index d7e34ab1..702213db 100644 --- a/perf_hooks/performance_measure_name_startmark_endmark.md +++ b/perf_hooks/performance_measure_name_startmark_endmark.md @@ -1,10 +1,14 @@ * `name` {string} -* `startMark` {string} -* `endMark` {string} +* `startMark` {string} Optional. +* `endMark` {string} Optional. Creates a new `PerformanceMeasure` entry in the Performance Timeline. A `PerformanceMeasure` is a subclass of `PerformanceEntry` whose @@ -17,8 +21,9 @@ Performance Timeline, or *may* identify any of the timestamp properties provided by the `PerformanceNodeTiming` class. If the named `startMark` does not exist, then `startMark` is set to [`timeOrigin`][] by default. -The `endMark` argument must identify any *existing* `PerformanceMark` in the -Performance Timeline or any of the timestamp properties provided by the -`PerformanceNodeTiming` class. If the named `endMark` does not exist, an +The optional `endMark` argument must identify any *existing* `PerformanceMark` +in the Performance Timeline or any of the timestamp properties provided by the +`PerformanceNodeTiming` class. `endMark` will be `performance.now()` +if no parameter is passed, otherwise if the named `endMark` does not exist, an error will be thrown. diff --git a/perf_hooks/performance_timing_api.md b/perf_hooks/performance_timing_api.md index 734043e7..9fe9935c 100644 --- a/perf_hooks/performance_timing_api.md +++ b/perf_hooks/performance_timing_api.md @@ -16,9 +16,12 @@ const obs = new PerformanceObserver((items) => { performance.clearMarks(); }); obs.observe({ entryTypes: ['measure'] }); +performance.measure('Start to Now'); performance.mark('A'); doSomeLongRunningProcess(() => { + performance.measure('A to Now', 'A'); + performance.mark('B'); performance.measure('A to B', 'A', 'B'); }); diff --git a/perf_hooks/performanceentry_flags.md b/perf_hooks/performanceentry_flags.md new file mode 100644 index 00000000..8f7cffec --- /dev/null +++ b/perf_hooks/performanceentry_flags.md @@ -0,0 +1,18 @@ + + +* {number} + +When `performanceEntry.entryType` is equal to `'gc'`, the `performance.flags` +property contains additional information about garbage collection operation. +The value may be one of: + +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE` + diff --git a/policy/example_patched_dependency.md b/policy/example_patched_dependency.md index 538c8d15..5a9b61a5 100644 --- a/policy/example_patched_dependency.md +++ b/policy/example_patched_dependency.md @@ -1,7 +1,7 @@ -Since a dependency can be redirected, you can provide attenuated or modified -forms of dependencies as fits your application. For example, you could log -data about timing of function durations by wrapping the original: +Redirected dependencies can provide attenuated or modified functionality as fits +the application. For example, log data about timing of function durations by +wrapping the original: ```js const original = require('fn'); diff --git a/process/event_uncaughtexception.md b/process/event_uncaughtexception.md index d62734a6..6a9b1693 100644 --- a/process/event_uncaughtexception.md +++ b/process/event_uncaughtexception.md @@ -33,3 +33,5 @@ nonexistentFunc(); console.log('这里不会运行'); ``` +通过安装 `'uncaughtExceptionMonitor'` 监听器,可以监视 `'uncaughtException'` 事件,而不会覆盖默认行为以退出该进程。 + diff --git a/process/event_uncaughtexceptionmonitor.md b/process/event_uncaughtexceptionmonitor.md new file mode 100644 index 00000000..49ac543e --- /dev/null +++ b/process/event_uncaughtexceptionmonitor.md @@ -0,0 +1,27 @@ + + +* `err` {Error} The uncaught exception. +* `origin` {string} Indicates if the exception originates from an unhandled + rejection or from synchronous errors. Can either be `'uncaughtException'` or + `'unhandledRejection'`. + +The `'uncaughtExceptionMonitor'` event is emitted before an +`'uncaughtException'` event is emitted or a hook installed via +[`process.setUncaughtExceptionCaptureCallback()`][] is called. + +Installing an `'uncaughtExceptionMonitor'` listener does not change the behavior +once an `'uncaughtException'` event is emitted. The process will +still crash if no `'uncaughtException'` listener is installed. + +```js +process.on('uncaughtExceptionMonitor', (err, origin) => { + MyMonitoringTool.logSync(err, origin); +}); + +// Intentionally cause an exception, but don't catch it. +nonexistentFunc(); +// Still crashes Node.js +``` + diff --git a/process/process_channel.md b/process/process_channel.md index db9bc9eb..319e5cc7 100644 --- a/process/process_channel.md +++ b/process/process_channel.md @@ -1,5 +1,9 @@ * {Object} diff --git a/process/process_channel_ref.md b/process/process_channel_ref.md new file mode 100644 index 00000000..407be5bc --- /dev/null +++ b/process/process_channel_ref.md @@ -0,0 +1,11 @@ + + +This method makes the IPC channel keep the event loop of the process +running if `.unref()` has been called before. + +Typically, this is managed through the number of `'disconnect'` and `'message'` +listeners on the `process` object. However, this method can be used to +explicitly request a specific behavior. + diff --git a/process/process_channel_unref.md b/process/process_channel_unref.md new file mode 100644 index 00000000..a7059000 --- /dev/null +++ b/process/process_channel_unref.md @@ -0,0 +1,11 @@ + + +This method makes the IPC channel not keep the event loop of the process +running, and lets it finish even while the channel is open. + +Typically, this is managed through the number of `'disconnect'` and `'message'` +listeners on the `process` object. However, this method can be used to +explicitly request a specific behavior. + diff --git a/process/process_mainmodule.md b/process/process_mainmodule.md index 27c362fd..75a07dbc 100644 --- a/process/process_mainmodule.md +++ b/process/process_mainmodule.md @@ -1,12 +1,18 @@ +> Stability: 0 - Deprecated: Use [`require.main`][] instead. + * {Object} -`process.mainModule` 属性提供了一种获取 [`require.main`] 的替代方式。 -区别在于,若主模块在运行时中发生改变,[`require.main`] 可能仍然指向变化之前所依赖的模块。 -一般来说,假定两者指向相同的模块是安全的。 +The `process.mainModule` property provides an alternative way of retrieving +[`require.main`][]. The difference is that if the main module changes at +runtime, [`require.main`][] may still refer to the original main module in +modules that were required before the change occurred. Generally, it's +safe to assume that the two refer to the same module. -就像 [`require.main`][] 一样,如果没有入口脚本,`process.mainModule` 的值是 `undefined`。 +As with [`require.main`][], `process.mainModule` will be `undefined` if there +is no entry script. diff --git a/process/process_memoryusage.md b/process/process_memoryusage.md index bf74d26a..4fecbfcf 100644 --- a/process/process_memoryusage.md +++ b/process/process_memoryusage.md @@ -1,16 +1,20 @@ * 返回: {Object} - * `rss` {integer} - * `heapTotal` {integer} - * `heapUsed` {integer} - * `external` {integer} + * `rss` {integer} + * `heapTotal` {integer} + * `heapUsed` {integer} + * `external` {integer} + * `arrayBuffers` {integer} `process.memoryUsage()` 方法返回 Node.js 进程的内存使用情况的对象,该对象每个属性值的单位为字节。 @@ -28,16 +32,17 @@ console.log(process.memoryUsage()); rss: 4935680, heapTotal: 1826816, heapUsed: 650472, - external: 49879 + external: 49879, + arrayBuffers: 9386 } ``` -`heapTotal` 和 `heapUsed` 代表 V8 的内存使用情况。 -`external` 代表 V8 管理的,绑定到 Javascript 的 C++ 对象的内存使用情况。 -`rss` 是驻留集大小, 是给这个进程分配了多少物理内存(占总分配内存的一部分),这些物理内存中包含堆、代码段、以及栈。 - -对象、字符串、闭包等存于堆内存。 -变量存于栈内存,实际的 JavaScript 源代码存于代码段内存。 +* `heapTotal` 和 `heapUsed` 代表 V8 的内存使用情况。 +* `external` 代表 V8 管理的,绑定到 Javascript 的 C++ 对象的内存使用情况。 +* `rss` 是驻留集大小, 是给这个进程分配了多少物理内存(占总分配内存的一部分),包含所有的 C++ 和 JavaScript 对象与代码。 +* `arrayBuffers` 指分配给 `ArrayBuffer` 和 `SharedArrayBuffer` 的内存,包括所有的 Node.js [`Buffer`]。 + 这也包含在 `external` 值中。 + 当 Node.js 用作嵌入式库时,此值可能为 `0`,因为在这种情况下可能无法跟踪 `ArrayBuffer` 的分配。 使用 [`Worker`] 线程时,`rss` 将会是一个对整个进程有效的值,而其他字段只指向当前线程。 diff --git a/process/process_report.md b/process/process_report.md index ba7faee1..0415bde3 100644 --- a/process/process_report.md +++ b/process/process_report.md @@ -1,9 +1,11 @@ -> Stability: 1 - Experimental - * {Object} `process.report` is an object whose methods are used to generate diagnostic diff --git a/process/process_report_compact.md b/process/process_report_compact.md new file mode 100644 index 00000000..0a8b4d94 --- /dev/null +++ b/process/process_report_compact.md @@ -0,0 +1,14 @@ + + +* {boolean} + +Write reports in a compact format, single-line JSON, more easily consumable +by log processing systems than the default multi-line format designed for +human consumption. + +```js +console.log(`Reports are compact? ${process.report.compact}`); +``` + diff --git a/process/process_report_directory.md b/process/process_report_directory.md index b8ba3513..ff338343 100644 --- a/process/process_report_directory.md +++ b/process/process_report_directory.md @@ -1,9 +1,11 @@ -> Stability: 1 - Experimental - * {string} Directory where the report is written. The default value is the empty string, diff --git a/process/process_report_filename.md b/process/process_report_filename.md index 49f61c2e..5ca0d3bc 100644 --- a/process/process_report_filename.md +++ b/process/process_report_filename.md @@ -1,9 +1,11 @@ -> Stability: 1 - Experimental - * {string} Filename where the report is written. If set to the empty string, the output diff --git a/process/process_report_getreport_err.md b/process/process_report_getreport_err.md index 489bc008..c176c927 100644 --- a/process/process_report_getreport_err.md +++ b/process/process_report_getreport_err.md @@ -1,9 +1,11 @@ -> Stability: 1 - Experimental - * `err` {Error} A custom error used for reporting the JavaScript stack. * Returns: {Object} diff --git a/process/process_report_reportonsignal.md b/process/process_report_reportonsignal.md index 6af9ea5e..de743f7a 100644 --- a/process/process_report_reportonsignal.md +++ b/process/process_report_reportonsignal.md @@ -1,9 +1,11 @@ -> Stability: 1 - Experimental - * {boolean} If `true`, a diagnostic report is generated when the process receives the diff --git a/process/process_report_reportonuncaughtexception.md b/process/process_report_reportonuncaughtexception.md index 23ae5ea5..e651c7dc 100644 --- a/process/process_report_reportonuncaughtexception.md +++ b/process/process_report_reportonuncaughtexception.md @@ -1,9 +1,11 @@ -> Stability: 1 - Experimental - * {boolean} If `true`, a diagnostic report is generated on uncaught exception. diff --git a/process/process_report_signal.md b/process/process_report_signal.md index 7f1b2afe..c92e6ce2 100644 --- a/process/process_report_signal.md +++ b/process/process_report_signal.md @@ -1,9 +1,11 @@ -> Stability: 1 - Experimental - * {string} The signal used to trigger the creation of a diagnostic report. Defaults to diff --git a/process/process_report_writereport_filename_err.md b/process/process_report_writereport_filename_err.md index 049f152d..b9aa5600 100644 --- a/process/process_report_writereport_filename_err.md +++ b/process/process_report_writereport_filename_err.md @@ -1,9 +1,11 @@ -> Stability: 1 - Experimental - * `filename` {string} Name of the file where the report is written. This should be a relative path, that will be appended to the directory specified in `process.report.directory`, or the current working directory of the Node.js diff --git a/process/process_umask.md b/process/process_umask.md new file mode 100644 index 00000000..583a6a08 --- /dev/null +++ b/process/process_umask.md @@ -0,0 +1,17 @@ + + +> Stability: 0 - Deprecated. Calling `process.umask()` with no argument causes +> the process-wide umask to be written twice. This introduces a race condition +> between threads, and is a potential security vulnerability. There is no safe, +> cross-platform alternative API. + +`process.umask()` returns the Node.js process's file mode creation mask. Child +processes inherit the mask from the parent process. + diff --git a/process/process_umask_mask.md b/process/process_umask_mask.md index 2159bc91..2181aca9 100644 --- a/process/process_umask_mask.md +++ b/process/process_umask_mask.md @@ -4,8 +4,10 @@ added: v0.1.19 * `mask` {string|integer} -`process.umask()`方法用于返回或设置Node.js进程的默认创建文件的权限掩码。子进程从父进程继承这个掩码。 -不传参数时,默认返回当前掩码,如果传递了参数,创建文件掩码就被设置为参数值,并且返回之前的掩码。 +`process.umask(mask)` 会设置 Node.js 进程的文件模式的创建掩码。 +子进程从父进程继承掩码。 +返回上一个掩码。 + ```js const newmask = 0o022; const oldmask = process.umask(newmask); @@ -14,6 +16,6 @@ console.log( ); ``` -[`Worker`] 线程能够读取 umask,但是尝试设置 umask 将会导致抛出异常。 +在 [`Worker`] 线程中,`process.umask(mask)` 会抛出异常。 diff --git a/process/process_versions.md b/process/process_versions.md index 9b703a4d..db76d886 100644 --- a/process/process_versions.md +++ b/process/process_versions.md @@ -32,7 +32,6 @@ console.log(process.versions); nghttp2: '1.34.0', napi: '4', llhttp: '1.1.1', - http_parser: '2.8.0', openssl: '1.1.1b', cldr: '34.0', icu: '63.1', diff --git a/process/signal_events.md b/process/signal_events.md index 6c10d60d..affd5e9d 100644 --- a/process/signal_events.md +++ b/process/signal_events.md @@ -43,9 +43,12 @@ process.on('SIGTERM', handle); * `'SIGSTOP'` 不能绑定监听器。 * `'SIGBUS'`、`'SIGFPE'`、`'SIGSEGV'` 和 `'SIGILL'`, 如果不是通过 kill(2) 产生,默认会使进程停留在某个状态,在此状态下尝试调用 JS 监听器是不安全的。 如果尝试调用 JS 监听器可能会导致进程在无限循环中挂死,因为使用 `process.on()` 附加的监听器是以异步的方式被调用,因此不能纠正隐含的问题。 +* 可以发送 `0` 来测试某个进程是否存在,如果该进程存在则没有影响,但是如果该进程不存在则会抛出错误。 -Windows 不支持发送信号,但是 Node.js 通过 [`process.kill()`][] 和 [`subprocess.kill()`][] 提供了某些模拟机制。 -发送信号 `0` 可以测试进程是否存在。 -发送 `SIGINT`、`SIGTERM` 和 `SIGKILL` 使得目标进程无条件终止。 +Windows 不支持信号,因此没有等效物来通过信号终止,但是 Node.js 提供了一些 [`process.kill()`] 和 [`subprocess.kill()`] 的模拟: + + +* 发送 `SIGINT`、`SIGTERM` 和 `SIGKILL` 会导致目标进程被无条件地终止,然后子进程会报告该进程已被信号终止。 +* 发送信号 `0` 可以用作与平台无关的方式来测试进程的存在性。 diff --git a/readline/readline_createinterface_options.md b/readline/readline_createinterface_options.md index 8c725a4a..fe93e082 100644 --- a/readline/readline_createinterface_options.md +++ b/readline/readline_createinterface_options.md @@ -1,6 +1,9 @@ * Returns: {Object} diff --git a/readline/rl_write_data_key.md b/readline/rl_write_data_key.md index f613964a..a4b80077 100644 --- a/readline/rl_write_data_key.md +++ b/readline/rl_write_data_key.md @@ -11,6 +11,7 @@ added: v0.1.98 `rl.write()` 方法将 `data` 或 `key` 标识的按键序列写入 `output`。 仅当 `output` 是 [TTY] 文本终端时才支持 `key` 参数。 +有快捷键组合的列表,请参阅 [TTY 快捷键][TTY keybindings]。 如果指定了 `key`,则忽略 `data`。 diff --git a/readline/tty_keybindings.md b/readline/tty_keybindings.md new file mode 100644 index 00000000..382d1b0f --- /dev/null +++ b/readline/tty_keybindings.md @@ -0,0 +1,136 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeybindingsDescriptionNotes
ctrl + shift + backspaceDelete line leftDoesn't work on Linux, Mac and Windows
ctrl + shift + deleteDelete line rightDoesn't work on Linux and Mac
ctrl + cEmit SIGINT or close the readline instance
ctrl + hDelete left
ctrl + dDelete right or close the readline instance in case the current line is empty / EOFDoesn't work on Windows
ctrl + uDelete from the current position to the line start
ctrl + kDelete from the current position to the end of line
ctrl + aGo to start of line
ctrl + eGo to to end of line
ctrl + bBack one character
ctrl + fForward one character
ctrl + lClear screen
ctrl + nNext history item
ctrl + pPrevious history item
ctrl + zMoves running process into background. Type + fg and press enter + to return.Doesn't work on Windows
ctrl + w or ctrl + + backspaceDelete backwards to a word boundaryctrl + backspace Doesn't + work as expected on Windows
ctrl + deleteDelete forward to a word boundaryDoesn't work on Mac
ctrl + left or + meta + bWord leftctrl + left Doesn't work + on Mac
ctrl + right or + meta + fWord rightctrl + right Doesn't work + on Mac
meta + d or meta + + deleteDelete word rightmeta + delete Doesn't work + on windows
meta + backspaceDelete word leftDoesn't work on Mac
+ + + + + + + + + + + + + diff --git a/repl/commands_and_special_keys.md b/repl/commands_and_special_keys.md index 60216072..a5624810 100644 --- a/repl/commands_and_special_keys.md +++ b/repl/commands_and_special_keys.md @@ -31,3 +31,6 @@ REPL 中下列按键组合有特殊作用: * `-D` - 与 `.exit` 命令的效果一样。 * `` - 当在空白行按下时,显示全局和本地作用域内的变量。当在输入时按下,显示相关的自动补全选项。 +有关与反向i搜索相关的快捷键,请参阅[反向i搜索][`reverse-i-search`]。 +有关所有的其他快捷键,请参阅 [TTY 快捷键][TTY keybindings]。 + diff --git a/repl/design_and_features.md b/repl/design_and_features.md index e1139467..062d5c0b 100644 --- a/repl/design_and_features.md +++ b/repl/design_and_features.md @@ -3,5 +3,7 @@ 当 [`repl.REPLServer`] 实例运行时,它接收用户输入的每一行,根据用户定义的解释函数解释这些输入,然后输出结果。 输入可以是 `stdin`,输出可以是 `stdout`,或者也可以连接到其他任何 Node.js [流][stream]。 -[`repl.REPLServer`] 实例支持输入的自动补全、精简 Emacs 风格的行编辑、多行输入、ANSI 风格的输出、当前 REPL 会话状态的保存与恢复、错误校正、以及可定制的解释函数。 +[`repl.REPLServer`] 实例支持输入的自动补全、完成的预览、精简 Emacs 风格的行编辑、多行输入、类似 [ZSH] 的反向i搜索、类似 [ZSH] 的基于子字符串的历史搜索、ANSI 风格的输出、当前 REPL 会话状态的保存与恢复、错误校正、以及可定制的解释函数。 +不支持 ANSI 风格和 Emacs 风格的行编辑的终端会自动地回退到有限的特性集。 + diff --git a/repl/repl_start_options.md b/repl/repl_start_options.md index 75197e00..a3030173 100644 --- a/repl/repl_start_options.md +++ b/repl/repl_start_options.md @@ -1,6 +1,9 @@ + +The REPL supports bi-directional reverse-i-search similar to [ZSH][]. It is +triggered with ` + R` to search backwards and ` + S` to search +forwards. + +Duplicated history entires will be skipped. + +Entries are accepted as soon as any button is pressed that doesn't correspond +with the reverse search. Cancelling is possible by pressing `escape` or +` + C`. + +Changing the direction immediately searches for the next entry in the expected +direction from the current position on. + diff --git a/report/configuration.md b/report/configuration.md index 2b8f8fd7..3c7ebf20 100644 --- a/report/configuration.md +++ b/report/configuration.md @@ -48,7 +48,7 @@ Configuration on module initialization is also available via environment variables: ```bash -NODE_OPTIONS="--experimental-report --report-uncaught-exception \ +NODE_OPTIONS="--report-uncaught-exception \ --report-on-fatalerror --report-on-signal \ --report-signal=SIGUSR2 --report-filename=./report.json \ --report-directory=/home/nodeuser" diff --git a/report/diagnostic_report.md b/report/diagnostic_report.md index 2949fb6b..1b29136d 100644 --- a/report/diagnostic_report.md +++ b/report/diagnostic_report.md @@ -2,7 +2,7 @@ -> Stability: 1 - Experimental +> Stability: 2 - Stable @@ -31,7 +31,6 @@ is provided below for reference. "cwd": "/home/nodeuser/project/node", "commandLine": [ "/home/nodeuser/project/node/out/Release/node", - "--experimental-report", "--report-uncaught-exception", "/home/nodeuser/project/node/test/report/test-exception.js", "child" @@ -52,7 +51,6 @@ is provided below for reference. "nghttp2": "1.34.0", "napi": "3", "llhttp": "1.0.1", - "http_parser": "2.8.0", "openssl": "1.1.0j" }, "release": { diff --git a/report/interaction_with_workers.md b/report/interaction_with_workers.md index 636df1d3..8e735890 100644 --- a/report/interaction_with_workers.md +++ b/report/interaction_with_workers.md @@ -1,6 +1,6 @@ diff --git a/report/usage.md b/report/usage.md index 3e9f5cab..a6df455f 100644 --- a/report/usage.md +++ b/report/usage.md @@ -1,13 +1,9 @@ ```bash -node --experimental-report --report-uncaught-exception \ - --report-on-signal --report-on-fatalerror app.js +node --report-uncaught-exception --report-on-signal \ +--report-on-fatalerror app.js ``` -* `--experimental-report` Enables the diagnostic report feature. - In the absence of this flag, use of all other related options will result in - an error. - * `--report-uncaught-exception` Enables report to be generated on un-caught exceptions. Useful when inspecting JavaScript stack in conjunction with native stack and other runtime environment data. @@ -32,6 +28,10 @@ that leads to termination of the application. Useful to inspect various diagnostic data elements such as heap, stack, event loop state, resource consumption etc. to reason about the fatal error. +* `--report-compact` Write reports in a compact format, single-line JSON, more +easily consumable by log processing systems than the default multi-line format +designed for human consumption. + * `--report-directory` Location at which the report will be generated. diff --git a/stream/api_for_stream_implementers.md b/stream/api_for_stream_implementers.md index 2734e1fc..d986033d 100644 --- a/stream/api_for_stream_implementers.md +++ b/stream/api_for_stream_implementers.md @@ -11,11 +11,7 @@ const { Writable } = require('stream'); class MyWritable extends Writable { constructor({ highWaterMark, ...options }) { - super({ - highWaterMark, - autoDestroy: true, - emitClose: true - }); + super({ highWaterMark }); // ... } } diff --git a/stream/constructor_new_stream_writable_options.md b/stream/constructor_new_stream_writable_options.md index 3406de4a..86c09805 100644 --- a/stream/constructor_new_stream_writable_options.md +++ b/stream/constructor_new_stream_writable_options.md @@ -8,6 +8,9 @@ changes: pr-url: https://github.com/nodejs/node/pull/22795 description: Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'finish'` or errors. + - version: v14.0.0 + pr-url: https://github.com/nodejs/node/pull/30623 + description: Change `autoDestroy` option default to `true`. --> * `options` {Object} @@ -23,7 +26,7 @@ changes: * `writev` {Function} 对 [`stream._writev()`][stream-_writev] 方法的实现。 * `destroy` {Function} 对 [`stream._destroy()`][writable-_destroy] 方法的实现。 * `final` {Function} 对 [`stream._final()`][stream-_final] 方法的实现。 - * `autoDestroy` {boolean} 此流是否应在结束后自动调用 `.destroy()`。**默认值:** `false`. + * `autoDestroy` {boolean} 此流是否应在结束后自动调用 `.destroy()`。**默认值:** `true`. ```js diff --git a/stream/event_error.md b/stream/event_error.md index e1c0bb90..7fc3ebd9 100644 --- a/stream/event_error.md +++ b/stream/event_error.md @@ -7,5 +7,8 @@ added: v0.9.4 如果在写入或管道数据时发生错误,则会触发 `'error'` 事件。 当调用时,监听器回调会传入一个 `Error` 参数。 -除非在创建流时将 [`autoDestroy`][writable-new] 选项设置为 `true`,否则在触发 `'error'` 事件时不会关闭流。 +除非在创建流时将 [`autoDestroy`][writable-new] 选项设置为 `false`,否则在触发 `'error'` 事件时流会被关闭。 + +在 `'error'` 之后,除 `'close'` 事件外,不应再触发其他事件(包括 `'error'` 事件)。 + diff --git a/stream/events_finish_and_end.md b/stream/events_finish_and_end.md index 0dd5e2b4..b0d47ea5 100644 --- a/stream/events_finish_and_end.md +++ b/stream/events_finish_and_end.md @@ -1,4 +1,5 @@ [`'finish'`] 事件来自 `stream.Writable` 类,[`'end'`] 事件来自 `stream.Readable` 类。 当调用了 [`stream.end()`][stream-end] 并且 [`stream._transform()`][stream-_transform] 处理完全部数据块之后,触发 `'finish'` 事件。 当调用了 [`transform._flush()`][stream-_flush] 中的回调函数并且所有数据已经输出之后,触发 `'end'` 事件。 +如果出现错误,则不应触发 `'finish'` 或 `'end'`。 diff --git a/stream/new_stream_readable_options.md b/stream/new_stream_readable_options.md index 35e32a95..b9a3e3c3 100644 --- a/stream/new_stream_readable_options.md +++ b/stream/new_stream_readable_options.md @@ -4,6 +4,9 @@ changes: pr-url: https://github.com/nodejs/node/pull/22795 description: Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'end'` or errors. + - version: v14.0.0 + pr-url: https://github.com/nodejs/node/pull/30623 + description: Change `autoDestroy` option default to `true`. --> * `options` {Object} @@ -17,7 +20,7 @@ changes: * `emitClose` {boolean} 流被销毁后是否应该触发 `'close'`。**默认值:** `true`。 * `read` {Function} 对 [`stream._read()`][stream-_read] 方法的实现。 * `destroy` {Function} 对 [`stream._destroy()`][readable-_destroy] 方法的实现。 - * `autoDestroy` {boolean} 流是否应在结束后自动调用 `.destroy()`。**默认值:** `false`。 + * `autoDestroy` {boolean} 流是否应在结束后自动调用 `.destroy()`。**默认值:** `true`。 ```js diff --git a/stream/piping_to_writable_streams_from_async_iterators.md b/stream/piping_to_writable_streams_from_async_iterators.md index 34301830..43acef5f 100644 --- a/stream/piping_to_writable_streams_from_async_iterators.md +++ b/stream/piping_to_writable_streams_from_async_iterators.md @@ -64,8 +64,7 @@ const pipeline = util.promisify(stream.pipeline); const writable = fs.createWriteStream('./file'); (async function() { - const readable = Readable.from(iterable); - await pipeline(readable, writable); + await pipeline(iterable, writable); })(); ``` diff --git a/stream/readable_destroy_error.md b/stream/readable_destroy_error.md index 6c7477ec..1d83ac06 100644 --- a/stream/readable_destroy_error.md +++ b/stream/readable_destroy_error.md @@ -8,5 +8,8 @@ added: v8.0.0 销毁流。 可选地触发 `'error'` 事件,并触发 `'close'` 事件(除非将 `emitClose` 设置为 `false`)。 在此调用之后,可读流将会释放所有内部的资源,并且将会忽略对 `push()` 的后续调用。 + +一旦调用 `destroy()`,则不会再执行任何其他操作,并且除了 `_destroy` 以外的其他错误都不会作为 `'error'` 触发。 + 实现者不应该重写此方法,而应该实现 [`readable._destroy()`][readable-_destroy]。 diff --git a/stream/readable_readable.md b/stream/readable_readable.md index 8fdcf976..c0268a31 100644 --- a/stream/readable_readable.md +++ b/stream/readable_readable.md @@ -4,5 +4,5 @@ added: v11.4.0 * {boolean} -如果可以安全地调用 [`readable.read()`][stream-read],则为 `true`。 +如果可以安全地调用 [`readable.read()`][stream-read](这意味着流没有被破坏或触发 `'error'` 或 `'end'`),则为 `true`。 diff --git a/stream/stream_pipeline_streams_callback.md b/stream/stream_pipeline_source_transforms_destination_callback.md similarity index 55% rename from stream/stream_pipeline_streams_callback.md rename to stream/stream_pipeline_source_transforms_destination_callback.md index c42a08f2..b666f696 100644 --- a/stream/stream_pipeline_streams_callback.md +++ b/stream/stream_pipeline_source_transforms_destination_callback.md @@ -1,12 +1,25 @@ -* `...streams` {Stream} 要使用管道传送的两个或多个流。 +* `source` {Stream|Iterable|AsyncIterable|Function} + * Returns: {Iterable|AsyncIterable} +* `...transforms` {Stream|Function} + * `source` {AsyncIterable} + * Returns: {AsyncIterable} +* `destination` {Stream|Function} + * `source` {AsyncIterable} + * Returns: {AsyncIterable|Promise} * `callback` {Function} 当管道完全地完成时调用。 * `err` {Error} + * `val` `destination` 返回的 `Promise` 的 resolve 的值。 +* 返回: {Stream} -一个模块方法,使用管道传送多个流,并转发错误和正确地清理,当管道完成时提供回调。 +一个模块方法,使用管道传送多个流和生成器,并转发错误和正确地清理,当管道完成时提供回调。 ```js const { pipeline } = require('stream'); @@ -48,6 +61,28 @@ async function run() { run().catch(console.error); ``` +`pipeline` API 还支持异步的生成器: + +```js +const pipeline = util.promisify(stream.pipeline); +const fs = require('fs').promises; + +async function run() { + await pipeline( + fs.createReadStream('lowercase.txt'), + async function* (source) { + for await (const chunk of source) { + yield String(chunk).toUpperCase(); + } + }, + fs.createWriteStream('uppercase.txt') + ); + console.log('Pipeline 成功'); +} + +run().catch(console.error); +``` + `stream.pipeline()` 将会在所有的流上调用 `stream.destroy(err)`,除了: * 已触发 `'end'` 或 `'close'` 的 `Readable` 流。 * 已触发 `'finish'` 或 `'close'` 的 `Writable` 流。 diff --git a/stream/stream_readable_from_iterable_options.md b/stream/stream_readable_from_iterable_options.md index f1e7df1f..f4a6ea09 100644 --- a/stream/stream_readable_from_iterable_options.md +++ b/stream/stream_readable_from_iterable_options.md @@ -1,5 +1,7 @@ * `iterable` {Iterable} 实现 `Symbol.asyncIterator` 或 `Symbol.iterator` 可迭代协议的对象。 diff --git a/stream/transform_destroy_error.md b/stream/transform_destroy_error.md index e025110c..11c5b4d4 100644 --- a/stream/transform_destroy_error.md +++ b/stream/transform_destroy_error.md @@ -3,9 +3,12 @@ added: v8.0.0 --> * `error` {Error} +* 返回: {this} 销毁流,并可选地触发 `'error'` 事件。 调用该方法后,transform 流会释放全部内部资源。 实现者不应该重写此方法,而应该实现 [`readable._destroy()`][readable-_destroy]。 `Transform` 流的 `_destroy()` 方法的默认实现会触发 `'close'` 事件,除非 `emitClose` 被设置为 `false`。 +一旦调用 `destroy()`,则不会再执行任何其他操作,并且除了 `_destroy` 以外的其他错误都不会作为 `'error'` 触发。 + diff --git a/stream/writable_destroy_error.md b/stream/writable_destroy_error.md index e6b92df0..adea8cd2 100644 --- a/stream/writable_destroy_error.md +++ b/stream/writable_destroy_error.md @@ -11,5 +11,8 @@ added: v8.0.0 这是销毁流的最直接的方式。 前面对 `write()` 的调用可能没有耗尽,并且可能触发 `ERR_STREAM_DESTROYED` 错误。 如果数据在关闭之前应该刷新,则使用 `end()` 而不是销毁,或者在销毁流之前等待 `'drain'` 事件。 + +一旦调用 `destroy()`,则不会再执行任何其他操作,并且除了 `_destroy` 以外的其他错误都不会作为 `'error'` 触发。 + 实现者不应该重写此方法,而应该实现 [`writable._destroy()`][writable-_destroy]。 diff --git a/stream/writable_end_chunk_encoding_callback.md b/stream/writable_end_chunk_encoding_callback.md index 45a3d27e..f02c1232 100644 --- a/stream/writable_end_chunk_encoding_callback.md +++ b/stream/writable_end_chunk_encoding_callback.md @@ -1,6 +1,9 @@ * {integer} diff --git a/stream/writable_write_chunk_encoding_callback.md b/stream/writable_write_chunk_encoding_callback.md index 2b5c4fd0..5465fcd4 100644 --- a/stream/writable_write_chunk_encoding_callback.md +++ b/stream/writable_write_chunk_encoding_callback.md @@ -20,6 +20,7 @@ changes: `writable.write()` 写入数据到流,并在数据被完全处理之后调用 `callback`。 如果发生错误,则 `callback` 可能被调用也可能不被调用。 为了可靠地检测错误,可以为 `'error'` 事件添加监听器。 +`callback` 会在触发 `'error'` 之前被异步地调用。 在接收了 `chunk` 后,如果内部的缓冲小于创建流时配置的 `highWaterMark`,则返回 `true` 。 如果返回 `false` ,则应该停止向流写入数据,直到 [`'drain'`][] 事件被触发。 diff --git a/stream/writable_write_chunk_encoding_callback_1.md b/stream/writable_write_chunk_encoding_callback_1.md index 5354f0c2..59fd4467 100644 --- a/stream/writable_write_chunk_encoding_callback_1.md +++ b/stream/writable_write_chunk_encoding_callback_1.md @@ -18,7 +18,7 @@ changes: 该函数不能被应用程序代码直接调用。 它应该由子类实现,且只能被内部的 `Writable` 类的方法调用。 -无论是成功完成写入还是写入失败出现错误,都必须调用 `callback`。 +必须在 `writable._write()` 内部同步地调用、或异步地(即不同的时间点)调用 `callback` 函数,以表明写入成功完成或因错误而失败。 如果调用失败,则 `callback` 的第一个参数必须是 `Error` 对象。 如果写入成功,则 `callback` 的第一个参数为 `null`。 diff --git a/tls/tls_connect_options_callback.md b/tls/tls_connect_options_callback.md index 56154c56..c595ff6c 100644 --- a/tls/tls_connect_options_callback.md +++ b/tls/tls_connect_options_callback.md @@ -1,7 +1,7 @@ + +* `length` {number} number of bytes to retrieve from keying material +* `label` {string} an application specific label, typically this will be a +value from the +[IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). +* `context` {Buffer} Optionally provide a context. + +* Returns: {Buffer} requested bytes of the keying material + +Keying material is used for validations to prevent different kind of attacks in +network protocols, for example in the specifications of IEEE 802.1X. + +Example + +```js +const keyingMaterial = tlsSocket.exportKeyingMaterial( + 128, + 'client finished'); + +/** + Example return value of keyingMaterial: + +*/ +``` +See the OpenSSL [`SSL_export_keying_material`][] documentation for more +information. + diff --git a/tls/tlssocket_getcipher.md b/tls/tlssocket_getcipher.md index 69dc5114..6ea95392 100644 --- a/tls/tlssocket_getcipher.md +++ b/tls/tlssocket_getcipher.md @@ -5,7 +5,7 @@ changes: pr-url: https://github.com/nodejs/node/pull/26625 description: Return the minimum cipher version, instead of a fixed string (`'TLSv1/SSLv3'`). - - version: v12.16.0 + - version: v13.4.0 pr-url: https://github.com/nodejs/node/pull/30637 description: Return the IETF cipher name as `standardName`. --> diff --git a/util/encodings_requiring_full_icu_data.md b/util/encodings_supported_by_default_with_full_icu_data.md similarity index 97% rename from util/encodings_requiring_full_icu_data.md rename to util/encodings_supported_by_default_with_full_icu_data.md index 76ab1ea9..6d21ff70 100644 --- a/util/encodings_requiring_full_icu_data.md +++ b/util/encodings_supported_by_default_with_full_icu_data.md @@ -36,6 +36,3 @@ | `'shift_jis'` | `'csshiftjis'`, `'ms932'`, `'ms_kanji'`, `'shift-jis'`, `'sjis'`, `'windows-31j'`, `'x-sjis'` | | `'euc-kr'` | `'cseuckr'`, `'csksc56011987'`, `'iso-ir-149'`, `'korean'`, `'ks_c_5601-1987'`, `'ks_c_5601-1989'`, `'ksc5601'`, `'ksc_5601'`, `'windows-949'` | -The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][] -is not supported. - diff --git a/util/encodings_supported_without_icu.md b/util/encodings_supported_when_icu_is_disabled.md similarity index 70% rename from util/encodings_supported_without_icu.md rename to util/encodings_supported_when_icu_is_disabled.md index efd2aff0..8ff93a0f 100644 --- a/util/encodings_supported_without_icu.md +++ b/util/encodings_supported_when_icu_is_disabled.md @@ -4,3 +4,6 @@ | `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | | `'utf-16le'` | `'utf-16'` | +The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][] +is not supported. + diff --git a/util/encodings_supported_by_default_with_icu.md b/util/encodings_supported_when_node_js_is_built_with_the_small_icu_option.md similarity index 100% rename from util/encodings_supported_by_default_with_icu.md rename to util/encodings_supported_when_node_js_is_built_with_the_small_icu_option.md diff --git a/util/new_textdecoder_encoding_options.md b/util/new_textdecoder_encoding_options.md index c14fe09e..a725d803 100644 --- a/util/new_textdecoder_encoding_options.md +++ b/util/new_textdecoder_encoding_options.md @@ -9,9 +9,9 @@ changes: * `encoding` {string} Identifies the `encoding` that this `TextDecoder` instance supports. **Default:** `'utf-8'`. * `options` {Object} - * `fatal` {boolean} `true` if decoding failures are fatal. This option is only - supported when ICU is enabled (see [Internationalization][]). **Default:** - `false`. + * `fatal` {boolean} `true` if decoding failures are fatal. + This option is not supported when ICU is disabled + (see [Internationalization][]). **Default:** `false`. * `ignoreBOM` {boolean} When `true`, the `TextDecoder` will include the byte order mark in the decoded result. When `false`, the byte order mark will be removed from the output. This option is only used when `encoding` is diff --git a/util/util_inspect_object_showhidden_depth_colors.md b/util/util_inspect_object_showhidden_depth_colors.md index ac8c09ba..a20ce4fd 100644 --- a/util/util_inspect_object_showhidden_depth_colors.md +++ b/util/util_inspect_object_showhidden_depth_colors.md @@ -1,10 +1,16 @@ diff --git a/util/util_types_iswebassemblycompiledmodule_value.md b/util/util_types_iswebassemblycompiledmodule_value.md index ff0bc347..3164e4e0 100644 --- a/util/util_types_iswebassemblycompiledmodule_value.md +++ b/util/util_types_iswebassemblycompiledmodule_value.md @@ -1,7 +1,10 @@ +> Stability: 0 - Deprecated: Use `value instanceof WebAssembly.Module` instead. + * `value` {any} * Returns: {boolean} diff --git a/util/whatwg_supported_encodings.md b/util/whatwg_supported_encodings.md index 5f364fc0..8fb11aa5 100644 --- a/util/whatwg_supported_encodings.md +++ b/util/whatwg_supported_encodings.md @@ -4,7 +4,5 @@ Per the [WHATWG Encoding Standard][], the encodings supported by the one or more aliases may be used. Different Node.js build configurations support different sets of encodings. -While a very basic set of encodings is supported even on Node.js builds without -ICU enabled, support for some encodings is provided only when Node.js is built -with ICU and using the full ICU data (see [Internationalization][]). +(see [Internationalization][]) diff --git a/vm/class_vm_module.md b/vm/class_vm_module.md index 087a27a7..1d9d15a5 100644 --- a/vm/class_vm_module.md +++ b/vm/class_vm_module.md @@ -1,5 +1,5 @@ > Stability: 1 - Experimental @@ -14,9 +14,8 @@ specification. Unlike `vm.Script` however, every `vm.Module` object is bound to a context from its creation. Operations on `vm.Module` objects are intrinsically asynchronous, -in contrast with the synchronous nature of `vm.Script` objects. With the help -of async functions, however, manipulating `vm.Module` objects is fairly -straightforward. +in contrast with the synchronous nature of `vm.Script` objects. The use of +'async' functions can help with manipulating `vm.Module` objects. Using a `vm.Module` object requires three distinct steps: creation/parsing, linking, and evaluation. These three steps are illustrated in the following diff --git a/vm/class_vm_syntheticmodule.md b/vm/class_vm_syntheticmodule.md index 4553cb14..3feaf7da 100644 --- a/vm/class_vm_syntheticmodule.md +++ b/vm/class_vm_syntheticmodule.md @@ -1,5 +1,5 @@ > Stability: 1 - Experimental diff --git a/vm/constructor_new_vm_script_code_options.md b/vm/constructor_new_vm_script_code_options.md index 8e572f36..c4891b5d 100644 --- a/vm/constructor_new_vm_script_code_options.md +++ b/vm/constructor_new_vm_script_code_options.md @@ -24,7 +24,7 @@ changes: 不推荐使用此选项,而应该使用 `script.createCachedData()`。**默认值:** `false`。 * `importModuleDynamically` {Function} 在调用 `import()` 时评估此模块期间调用。 如果未指定此选项,则对 `import()` 的调用将拒绝 [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`]。 - 此选项是 `--experimental-modules` 标志的实验 API 的一部分,不应被视为稳定。 + 此选项是试验的模块的 API 的一部分,不应被视为稳定。 * `specifier` {string} 传给 `import()` 的说明符。 * `module` {vm.Module} * 返回: {Module Namespace Object|vm.Module} 返回 `vm.Module` 以利用错误跟踪,并避免出现包含 `then` 函数导出的命名空间问题。 diff --git a/vm/constructor_new_vm_sourcetextmodule_code_options.md b/vm/constructor_new_vm_sourcetextmodule_code_options.md index 8d8f4298..0f6581fb 100644 --- a/vm/constructor_new_vm_sourcetextmodule_code_options.md +++ b/vm/constructor_new_vm_sourcetextmodule_code_options.md @@ -4,6 +4,10 @@ * `identifier` {string} String used in stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index. + * `cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or + `TypedArray`, or `DataView` with V8's code cache data for the supplied + source. The `code` must be the same as the module from which this + `cachedData` was created. * `context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in. * `lineOffset` {integer} Specifies the line number offset that is displayed diff --git a/vm/constructor_new_vm_syntheticmodule_exportnames_evaluatecallback_options.md b/vm/constructor_new_vm_syntheticmodule_exportnames_evaluatecallback_options.md index 748412a5..1b79d1c8 100644 --- a/vm/constructor_new_vm_syntheticmodule_exportnames_evaluatecallback_options.md +++ b/vm/constructor_new_vm_syntheticmodule_exportnames_evaluatecallback_options.md @@ -1,5 +1,5 @@ * `exportNames` {string[]} Array of names that will be exported from the module. diff --git a/vm/script_createcacheddata.md b/vm/script_createcacheddata.md index a1fd43f6..d19109b8 100644 --- a/vm/script_createcacheddata.md +++ b/vm/script_createcacheddata.md @@ -4,7 +4,7 @@ added: v10.6.0 * 返回: {Buffer} -创建一个可以被 Script 构造函数中 `cachedData` 选项使用的代码缓存。返回 Buffer。可以在任何时候不限次数地调用该方法。 +创建一个可以被 `Script` 构造函数中 `cachedData` 选项使用的代码缓存。返回 `Buffer`。可以在任何时候不限次数地调用该方法。 ```js const script = new vm.Script(` diff --git a/vm/script_runincontext_contextifiedsandbox_options.md b/vm/script_runincontext_contextifiedsandbox_options.md deleted file mode 100644 index 20ffbd1e..00000000 --- a/vm/script_runincontext_contextifiedsandbox_options.md +++ /dev/null @@ -1,42 +0,0 @@ - - -* `contextifiedSandbox` {Object} 由 `vm.createContext()` 返回的[上下文隔离化][contextified]的对象。 -* `options` {Object} - * `displayErrors` {boolean} 当值为 `true` 的时候,假如在解析代码的时候发生错误 [`Error`][],引起错误的行将会被加入堆栈跟踪信息。**默认值:** `true`。 - * `timeout` {integer} 定义在被终止执行之前此 `code` 被允许执行的最大毫秒数。假如执行被终止,将会抛出一个错误 [`Error`][]。该值必须是严格正整数。 - * `breakOnSigint` {boolean} 若值为 `true`,当收到 `SIGINT` (Ctrl+C)事件时,代码会被终止执行。 - 此外,通过 `process.on('SIGINT')` 方法所设置的消息响应机制在代码被执行时会被屏蔽,但代码被终止后会被恢复。如果执行被终止,一个错误 [`Error`][] 会被抛出。**默认值:** `false`。 -* 返回: {any} 脚本中执行的最后一个语句的结果。 - -在指定的 `contextifiedSandbox` 中执行 `vm.Script` 对象中被编译后的代码并返回其结果。被执行的代码无法获取本地作用域。 - -以下的例子会编译一段代码,该代码会递增一个全局变量,给另外一个全局变量赋值。同时该代码被编译后会被多次执行。全局变量会被置于 `sandbox` 对象内。 - -```js -const util = require('util'); -const vm = require('vm'); - -const sandbox = { - animal: 'cat', - count: 2 -}; - -const script = new vm.Script('count += 1; name = "kitty";'); - -const context = vm.createContext(sandbox); -for (let i = 0; i < 10; ++i) { - script.runInContext(context); -} - -console.log(util.inspect(sandbox)); - -// { animal: 'cat', count: 12, name: 'kitty' } -``` - -使用 `timeout` 或者 `breakOnSigint` 选项会导致若干新的事件循环以及对应的线程,这有一个非零的性能消耗。 diff --git a/vm/script_runinnewcontext_sandbox_options.md b/vm/script_runinnewcontext_sandbox_options.md deleted file mode 100644 index 042f18ba..00000000 --- a/vm/script_runinnewcontext_sandbox_options.md +++ /dev/null @@ -1,45 +0,0 @@ - - -* `sandbox` {Object} 一个将会被[上下文隔离化][contextified]的对象。如果是 `undefined`, 则会生成一个新的对象。 -* `options` {Object} - * `displayErrors` {boolean} 当值为 `true` 的时候,假如在解析代码的时候发生错误 [`Error`][],引起错误的行将会被加入堆栈跟踪信息。**默认值:** `true`。 - * `timeout` {integer} 定义在被终止执行之前此 `code` 被允许执行的最大毫秒数。假如执行被终止,将会抛出一个错误 [`Error`][]。该值必须是严格正整数。 - * `breakOnSigint` {boolean} 若值为 `true`,当收到 `SIGINT` (Ctrl+C)事件时,代码会被终止执行。 - 此外,通过 `process.on('SIGINT')` 方法所设置的消息响应机制在代码被执行时会被屏蔽,但代码被终止后会被恢复。如果执行被终止,一个错误 [`Error`][] 会被抛出。**默认值:** `false`。 - * `contextName` {string} 新创建的上下文的人类可读名称。 **默认值:** `'VM Context i'`,其中 `i` 是创建的上下文的升序数字索引。 - * `contextOrigin` {string} 对应于新创建用于显示目的的上下文的[原点][origin]。 - 原点应格式化为类似一个 URL,但只包含协议,主机和端口(如果需要),例如 [`URL`] 对象的 [`url.origin`] 属性的值。 最值得注意的是,此字符串应省略尾部斜杠,因为它表示路径。 **默认值:** `''`。 - * `contextCodeGeneration` {Object} - * `strings` {boolean} 如果设置为 `false`,则对 `eval` 或函数构造函数(`Function`、`GeneratorFunction` 等)的任何调用都将抛出 `EvalError`。**默认值:** `true`。 - * `wasm` {boolean} 如果设置为 `false`,则任何编译 WebAssembly 模块的尝试都将抛出 `WebAssembly.CompileError`。**默认值:** `true`。 -* 返回: {any} 脚本中执行的最后一个语句的结果。 - -首先给指定的 `sandbox` 提供一个隔离的上下文, 再在此上下文中执行 `vm.Script` 中被编译的代码,最后返回结果。运行中的代码无法获取本地作用域。 - -以下的例子会编译一段代码,该代码会递增一个全局变量,给另外一个全局变量赋值。同时该代码被编译后会被多次执行。全局变量会被置于各个独立的 `sandbox` 对象内。 - -```js -const util = require('util'); -const vm = require('vm'); - -const script = new vm.Script('globalVar = "set"'); - -const sandboxes = [{}, {}, {}]; -sandboxes.forEach((sandbox) => { - script.runInNewContext(sandbox); -}); - -console.log(util.inspect(sandboxes)); - -// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] -``` - diff --git a/vm/sourcetextmodule_createcacheddata.md b/vm/sourcetextmodule_createcacheddata.md new file mode 100644 index 00000000..feeca0a1 --- /dev/null +++ b/vm/sourcetextmodule_createcacheddata.md @@ -0,0 +1,21 @@ + + +* Returns: {Buffer} + +Creates a code cache that can be used with the `SourceTextModule` constructor's +`cachedData` option. Returns a `Buffer`. This method may be called any number +of times before the module has been evaluated. + +```js +// Create an initial module +const module = new vm.SourceTextModule('const a = 1;'); + +// Create cached data from this module +const cachedData = module.createCachedData(); + +// Create a new module using the cached data. The code must be the same. +const module2 = new vm.SourceTextModule('const a = 1;', { cachedData }); +``` + diff --git a/vm/syntheticmodule_setexport_name_value.md b/vm/syntheticmodule_setexport_name_value.md index 8ca3d908..a8902674 100644 --- a/vm/syntheticmodule_setexport_name_value.md +++ b/vm/syntheticmodule_setexport_name_value.md @@ -1,5 +1,5 @@ * `name` {string} Name of the export to set. diff --git a/vm/vm_measurememory_options.md b/vm/vm_measurememory_options.md new file mode 100644 index 00000000..744eb625 --- /dev/null +++ b/vm/vm_measurememory_options.md @@ -0,0 +1,49 @@ + + + +> Stability: 1 - Experimental + +Measure the memory known to V8 and used by the current execution context +or a specified context. + +* `options` {Object} Optional. + * `mode` {string} Either `'summary'` or `'detailed'`. + **Default:** `'summary'` + * `context` {Object} Optional. A [contextified][] object returned + by `vm.createContext()`. If not specified, measure the memory + usage of the current context where `vm.measureMemory()` is invoked. +* Returns: {Promise} If the memory is successfully measured the promise will + resolve with an object containing information about the memory usage. + +The format of the object that the returned Promise may resolve with is +specific to the V8 engine and may change from one version of V8 to the next. + +The returned result is different from the statistics returned by +`v8.getHeapSpaceStatistics()` in that `vm.measureMemory()` measures +the memory reachable by V8 from a specific context, while +`v8.getHeapSpaceStatistics()` measures the memory used by an instance +of V8 engine, which can switch among multiple contexts that reference +objects in the heap of one engine. + +```js +const vm = require('vm'); +// Measure the memory used by the current context and return the result +// in summary. +vm.measureMemory({ mode: 'summary' }) + // Is the same as vm.measureMemory() + .then((result) => { + // The current format is: + // { total: { jsMemoryEstimate: 2211728, jsMemoryRange: [ 0, 2211728 ] } } + console.log(result); + }); + +const context = vm.createContext({}); +vm.measureMemory({ mode: 'detailed' }, context) + .then((result) => { + // At the moment the detailed format is the same as the summary one. + console.log(result); + }); +``` + diff --git a/vm/vm_runincontext_code_contextifiedobject_options.md b/vm/vm_runincontext_code_contextifiedobject_options.md index 1eb27150..0e6bad4d 100644 --- a/vm/vm_runincontext_code_contextifiedobject_options.md +++ b/vm/vm_runincontext_code_contextifiedobject_options.md @@ -24,7 +24,7 @@ changes: 不推荐使用此选项,而应该使用 `script.createCachedData()`。**默认值:** `false`。 * `importModuleDynamically` {Function} 在调用 `import()` 时评估此模块期间调用。 如果未指定此选项,则对 `import()` 的调用将拒绝 [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`]。 - 此选项是 `--experimental-modules` 标志的实验 API 的一部分,不应被视为稳定。 + 此选项是试验的模块的 API 的一部分,不应被视为稳定。 * `specifier` {string} 传给 `import()` 的说明符。 * `module` {vm.Module} * 返回: {Module Namespace Object|vm.Module} 返回 `vm.Module` 以利用错误跟踪,并避免出现包含 `then` 函数导出的命名空间问题。 diff --git a/vm/vm_runincontext_code_contextifiedsandbox_options.md b/vm/vm_runincontext_code_contextifiedsandbox_options.md deleted file mode 100644 index 47dff9bd..00000000 --- a/vm/vm_runincontext_code_contextifiedsandbox_options.md +++ /dev/null @@ -1,55 +0,0 @@ - - -* `code` {string} 将被编译和运行的 JavaScript 代码。 -* `contextifiedSandbox` {Object} 一个被[上下文隔离化][contextified]过的对象,会在 `code` 被编译和执行之后充当 `global` 对象。 -* `options` {Object|string} - * `filename` {string} 定义供脚本生成的堆栈跟踪信息所使用的文件名。**默认值:** `'evalmachine.'`。 - * `lineOffset` {number} 定义脚本生成的堆栈跟踪信息所显示的行号偏移。**默认值:** `0`。 - * `columnOffset` {number} 定义脚本生成的堆栈跟踪信息所显示的列号偏移。**默认值:** `0`。 - * `displayErrors` {boolean} 当值为 `true` 的时候,假如在解析代码的时候发生错误 [`Error`][],引起错误的行将会被加入堆栈跟踪信息。**默认值:** `true`。 - * `timeout` {integer} 定义在被终止执行之前此 `code` 被允许执行的最大毫秒数。假如执行被终止,将会抛出一个错误 [`Error`][]。该值必须是严格正整数。 - * `breakOnSigint` {boolean} 若值为 `true`,当收到 `SIGINT` (Ctrl+C)事件时,代码会被终止执行。 - 此外,通过 `process.on('SIGINT')` 方法所设置的消息响应机制在代码被执行时会被屏蔽,但代码被终止后会被恢复。如果执行被终止,一个错误 [`Error`][] 会被抛出。**默认值:** `false`。 - * `cachedData` {Buffer|TypedArray|DataView} 为源码提供一个可选的存有 V8 代码缓存数据的 `Buffer`、`TypedArray` 或 `TypedArray`。 - 如果提供了,则 `cachedDataRejected` 的值将会被设为要么为 `true` 要么为 `false`,这取决于 v8 引擎对数据的接受状况。 - * `produceCachedData` {boolean} 当值为 `true` 且 `cachedData` 不存在的时候,V8 将会试图为 `code` 生成代码缓存数据。 - 一旦成功,则一个有 V8 代码缓存数据的 `Buffer` 将会被生成和储存在返回的 `vm.Script` 实例的 `cachedData` 属性里。 - `cachedDataProduced` 的值会被设置为 `true` 或者 `false`,这取决于代码缓存数据是否被成功生成。 - 不推荐使用此选项,而应该使用 `script.createCachedData()`。**默认值:** `false`。 - * `importModuleDynamically` {Function} 在调用 `import()` 时评估此模块期间调用。 - 如果未指定此选项,则对 `import()` 的调用将拒绝 [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`]。 - 此选项是 `--experimental-modules` 标志的实验 API 的一部分,不应被视为稳定。 - * `specifier` {string} 传给 `import()` 的说明符。 - * `module` {vm.SourceTextModule} - * 返回: {Module Namespace Object|vm.SourceTextModule} 返回 `vm.SourceTextModule` 以利用错误跟踪,并避免出现包含 `then` 函数导出的命名空间问题。 -* 返回: {any} 脚本中执行的最后一个语句的结果。 - -`vm.runInContext()` 方法会编译 `code`,然后在指定的 `contextifiedSandbox` 的上下文里执行它并返回其结果。 -被执行的代码无法获取本地作用域。 -`contextifiedSandbox` 必须是事先被 [`vm.createContext()`] 方法[上下文隔离化][contextified]过的对象。 - -如果 `options` 是字符串,则它指定文件名。 - -以下例子使用一个单独的[上下文隔离化][contextified]过的对象来编译并运行几个不同的脚本: - -```js -const util = require('util'); -const vm = require('vm'); - -const sandbox = { globalVar: 1 }; -vm.createContext(sandbox); - -for (let i = 0; i < 10; ++i) { - vm.runInContext('globalVar *= 2;', sandbox); -} -console.log(util.inspect(sandbox)); - -// { globalVar: 1024 } -``` - diff --git a/vm/vm_runinnewcontext_code_contextobject_options.md b/vm/vm_runinnewcontext_code_contextobject_options.md index 8bfb7d7f..080a607b 100644 --- a/vm/vm_runinnewcontext_code_contextobject_options.md +++ b/vm/vm_runinnewcontext_code_contextobject_options.md @@ -33,7 +33,7 @@ changes: 不推荐使用此选项,而应该使用 `script.createCachedData()`。**默认值:** `false`。 * `importModuleDynamically` {Function} 在调用 `import()` 时评估此模块期间调用。 如果未指定此选项,则对 `import()` 的调用将拒绝 [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`]。 - 此选项是 `--experimental-modules` 标志的实验 API 的一部分,不应被视为稳定。 + 此选项是试验的模块的 API 的一部分,不应被视为稳定。 * `specifier` {string} 传给 `import()` 的说明符。 * `module` {vm.Module} * 返回: {Module Namespace Object|vm.Module} 返回 `vm.Module` 以利用错误跟踪,并避免出现包含 `then` 函数导出的命名空间问题。 diff --git a/vm/vm_runinnewcontext_code_sandbox_options.md b/vm/vm_runinnewcontext_code_sandbox_options.md deleted file mode 100644 index facdb030..00000000 --- a/vm/vm_runinnewcontext_code_sandbox_options.md +++ /dev/null @@ -1,63 +0,0 @@ - - -* `code` {string} 将被编译和运行的 JavaScript 代码。 -* `sandbox` {Object} 一个将会被[上下文隔离化][contextified]的对象。如果是 `undefined`, 则会生成一个新的对象。 -* `options` {Object|string} - * `filename` {string} 定义供脚本生成的堆栈跟踪信息所使用的文件名。**默认值:** `'evalmachine.'`。 - * `lineOffset` {number} 定义脚本生成的堆栈跟踪信息所显示的行号偏移。**默认值:** `0`。 - * `columnOffset` {number} 定义脚本生成的堆栈跟踪信息所显示的列号偏移。**默认值:** `0`。 - * `displayErrors` {boolean} 当值为 `true` 的时候,假如在解析代码的时候发生错误 [`Error`][],引起错误的行将会被加入堆栈跟踪信息。**默认值:** `true`。 - * `timeout` {integer} 定义在被终止执行之前此 `code` 被允许执行的最大毫秒数。假如执行被终止,将会抛出一个错误 [`Error`][]。该值必须是严格正整数。 - * `breakOnSigint` {boolean} 若值为 `true`,当收到 `SIGINT` (Ctrl+C)事件时,代码会被终止执行。 - 此外,通过 `process.on('SIGINT')` 方法所设置的消息响应机制在代码被执行时会被屏蔽,但代码被终止后会被恢复。如果执行被终止,一个错误 [`Error`][] 会被抛出。**默认值:** `false`。 - * `contextName` {string} 新创建的上下文的人类可读名称。 **默认值:** `'VM Context i'`,其中 `i` 是创建的上下文的升序数字索引。 - * `contextOrigin` {string} 对应于新创建用于显示目的的上下文的[原点][origin]。 - 原点应格式化为类似一个 URL,但只包含协议,主机和端口(如果需要),例如 [`URL`] 对象的 [`url.origin`] 属性的值。 最值得注意的是,此字符串应省略尾部斜杠,因为它表示路径。 **默认值:** `''`。 - * `contextCodeGeneration` {Object} - * `strings` {boolean} 如果设置为 `false`,则对 `eval` 或函数构造函数(`Function`、`GeneratorFunction` 等)的任何调用都将抛出 `EvalError`。**默认值:** `true`。 - * `wasm` {boolean} 如果设置为 `false`,则任何编译 WebAssembly 模块的尝试都将抛出 `WebAssembly.CompileError`。**默认值:** `true`。 - * `cachedData` {Buffer|TypedArray|DataView} 为源码提供一个可选的存有 V8 代码缓存数据的 `Buffer`、`TypedArray` 或 `TypedArray`。 - 如果提供了,则 `cachedDataRejected` 的值将会被设为要么为 `true` 要么为 `false`,这取决于 v8 引擎对数据的接受状况。 - * `produceCachedData` {boolean} 当值为 `true` 且 `cachedData` 不存在的时候,V8 将会试图为 `code` 生成代码缓存数据。 - 一旦成功,则一个有 V8 代码缓存数据的 `Buffer` 将会被生成和储存在返回的 `vm.Script` 实例的 `cachedData` 属性里。 - `cachedDataProduced` 的值会被设置为 `true` 或者 `false`,这取决于代码缓存数据是否被成功生成。 - 不推荐使用此选项,而应该使用 `script.createCachedData()`。**默认值:** `false`。 - * `importModuleDynamically` {Function} 在调用 `import()` 时评估此模块期间调用。 - 如果未指定此选项,则对 `import()` 的调用将拒绝 [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`]。 - 此选项是 `--experimental-modules` 标志的实验 API 的一部分,不应被视为稳定。 - * `specifier` {string} 传给 `import()` 的说明符。 - * `module` {vm.SourceTextModule} - * 返回: {Module Namespace Object|vm.SourceTextModule} 返回 `vm.SourceTextModule` 以利用错误跟踪,并避免出现包含 `then` 函数导出的命名空间问题。 -* 返回: {any} 脚本中执行的最后一个语句的结果。 - -`vm.runInNewContext()` 首先给指定的 `sandbox`(若为 `undefined`,则会新建一个` sandbox`)提供一个隔离的上下文, 再在此上下文中执行编译的 `code`,最后返回结果。 -运行中的代码无法获取本地作用域。 - -如果 `options` 是字符串,则它指定文件名。 - -以下的例子会编译一段代码,该代码会递增一个全局变量,给另外一个全局变量赋值。同时该代码被编译后会被多次执行。全局变量会被置于 `sandbox` 对象内。 - -```js -const util = require('util'); -const vm = require('vm'); - -const sandbox = { - animal: 'cat', - count: 2 -}; - -vm.runInNewContext('count += 1; name = "kitty"', sandbox); -console.log(util.inspect(sandbox)); - -// { animal: 'cat', count: 3, name: 'kitty' } -``` - diff --git a/vm/vm_runinthiscontext_code_options.md b/vm/vm_runinthiscontext_code_options.md index 0ed7c960..cbf4389f 100644 --- a/vm/vm_runinthiscontext_code_options.md +++ b/vm/vm_runinthiscontext_code_options.md @@ -23,7 +23,7 @@ changes: 不推荐使用此选项,而应该使用 `script.createCachedData()`。**默认值:** `false`。 * `importModuleDynamically` {Function} 在调用 `import()` 时评估此模块期间调用。 如果未指定此选项,则对 `import()` 的调用将拒绝 [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`]。 - 此选项是 `--experimental-modules` 标志的实验 API 的一部分,不应被视为稳定。 + 此选项是试验的模块的 API 的一部分,不应被视为稳定。 * `specifier` {string} 传给 `import()` 的说明符。 * `module` {vm.Module} * 返回: {Module Namespace Object|vm.Module} 返回 `vm.Module` 以利用错误跟踪,并避免出现包含 `then` 函数导出的命名空间问题。 diff --git a/wasi/class_wasi.md b/wasi/class_wasi.md index e4f9487b..557b410a 100644 --- a/wasi/class_wasi.md +++ b/wasi/class_wasi.md @@ -1,5 +1,5 @@ The `WASI` class provides the WASI system call API and additional convenience diff --git a/wasi/new_wasi_options.md b/wasi/new_wasi_options.md index 5eca14b4..f55709d9 100644 --- a/wasi/new_wasi_options.md +++ b/wasi/new_wasi_options.md @@ -1,5 +1,5 @@ * `options` {Object} @@ -12,4 +12,8 @@ added: v12.16.0 sandbox directory structure. The string keys of `preopens` are treated as directories within the sandbox. The corresponding values in `preopens` are the real paths to those directories on the host machine. + * `returnOnExit` {boolean} By default, WASI applications terminate the Node.js + process via the `__wasi_proc_exit()` function. Setting this option to `true` + causes `wasi.start()` to return the exit code rather than terminate the + process. **Default:** `false`. diff --git a/wasi/wasi_start_instance.md b/wasi/wasi_start_instance.md index 4556764c..1a69be3c 100644 --- a/wasi/wasi_start_instance.md +++ b/wasi/wasi_start_instance.md @@ -1,5 +1,5 @@ * `instance` {WebAssembly.Instance} diff --git a/wasi/wasi_wasiimport.md b/wasi/wasi_wasiimport.md index 20e2e5e3..98f1b771 100644 --- a/wasi/wasi_wasiimport.md +++ b/wasi/wasi_wasiimport.md @@ -1,5 +1,5 @@ * {Object} diff --git a/wasi/webassembly_system_interface_wasi.md b/wasi/webassembly_system_interface_wasi.md index fc926366..f8e073bb 100644 --- a/wasi/webassembly_system_interface_wasi.md +++ b/wasi/webassembly_system_interface_wasi.md @@ -1,5 +1,5 @@ - + > Stability: 1 - Experimental diff --git a/worker_threads/new_worker_filename_options.md b/worker_threads/new_worker_filename_options.md index c7f3e380..679b016c 100644 --- a/worker_threads/new_worker_filename_options.md +++ b/worker_threads/new_worker_filename_options.md @@ -1,15 +1,22 @@ -* `filename` {string} 工作线程主脚本的路径。必须是以 `./` 或 `../` 开头的绝对路径或相对路径(即相对于当前工作目录)。 +* `filename` {string} 工作线程主脚本的路径。必须是以 `./` 或 `../` 开头的绝对路径或相对路径(即相对于当前工作目录)、或者使用 `file:` 协议的 WHATWG `URL` 对象。 如果 `options.eval` 为 `true`,则这是一个包含 JavaScript 代码而不是路径的字符串。 * `options` {Object} * `argv` {any[]} 参数列表,其将会被字符串化并附加到工作线程中的 `process.argv`。 @@ -18,7 +25,7 @@ changes: 作为一个特殊值,[`worker.SHARE_ENV`] 可以用于指定父线程和子线程应该共享它们的环境变量。 在这种情况下,对一个线程的 `process.env` 对象的更改也会影响另一个线程。 **默认值:** `process.env`。 - * `eval` {boolean} 如果为 `true`,则将构造函数的第一个参数解释为工作线程联机后执行的脚本。 + * `eval` {boolean} 如果为 `true` 且第一个参数是一个 `string`,则将构造函数的第一个参数解释为工作线程联机后执行的脚本。 * `execArgv` {string[]} 传递给工作线程的 node CLI 选项的列表。 不支持 V8 选项(例如 `--max-old-space-size`)和影响进程的选项(例如 `--title`)。 如果设置,则它将会作为工作线程内部的 [`process.execArgv`] 提供。 diff --git a/worker_threads/worker_getheapsnapshot.md b/worker_threads/worker_getheapsnapshot.md new file mode 100644 index 00000000..ab0987ed --- /dev/null +++ b/worker_threads/worker_getheapsnapshot.md @@ -0,0 +1,14 @@ + + +* Returns: {Promise} A promise for a Readable Stream containing + a V8 heap snapshot + +Returns a readable stream for a V8 snapshot of the current state of the Worker. +See [`v8.getHeapSnapshot()`][] for more details. + +If the Worker thread is no longer running, which may occur before the +[`'exit'` event][] is emitted, the returned `Promise` will be rejected +immediately with an [`ERR_WORKER_NOT_RUNNING`][] error. + diff --git a/worker_threads/worker_resourcelimits.md b/worker_threads/worker_resourcelimits.md index 5607d447..1a6cc0d1 100644 --- a/worker_threads/worker_resourcelimits.md +++ b/worker_threads/worker_resourcelimits.md @@ -1,5 +1,5 @@ * {Object} diff --git a/worker_threads/worker_resourcelimits_1.md b/worker_threads/worker_resourcelimits_1.md index 07350ddf..1ec1bac9 100644 --- a/worker_threads/worker_resourcelimits_1.md +++ b/worker_threads/worker_resourcelimits_1.md @@ -1,5 +1,5 @@ * {Object} @@ -12,3 +12,4 @@ If the `resourceLimits` option was passed to the [`Worker`][] constructor, this matches its values. If the worker has stopped, the return value is an empty object. + diff --git a/worker_threads/worker_unref.md b/worker_threads/worker_unref.md index ae72e504..208b26b6 100644 --- a/worker_threads/worker_unref.md +++ b/worker_threads/worker_unref.md @@ -50,6 +50,8 @@ active handle in the event system. If the worker is already `unref()`ed calling + +