From 68287e295b8fdce7401a332e3cdd7a809c0d3667 Mon Sep 17 00:00:00 2001 From: h7lin Date: Thu, 23 Jul 2020 23:33:33 +0800 Subject: [PATCH] feat: 14.6.0 --- addons/callbacks.md | 4 +- addons/context_aware_addons.md | 3 +- addons/factory_of_wrapped_objects.md | 4 +- addons/function_arguments.md | 11 +- addons/function_factory.md | 5 +- addons/hello_world.md | 3 +- addons/object_factory.md | 4 +- addons/passing_wrapped_objects_around.md | 4 +- addons/wrapping_c_objects.md | 8 +- assert/assert.md | 2 + async_hooks/async_hooks.md | 2 + async_hooks/asynchronous_context_example.md | 37 +++-- async_hooks/resource.md | 2 +- buffer/buf_byteoffset.md | 6 +- buffer/buf_index.md | 2 +- buffer/buf_readbigint64be_offset.md | 13 ++ buffer/buf_readbigint64le_offset.md | 2 +- buffer/buf_readbiguint64be_offset.md | 18 +++ buffer/buf_readbiguint64le_offset.md | 5 +- buffer/buf_readdoublebe_offset.md | 21 +++ buffer/buf_readdoublele_offset.md | 4 +- buffer/buf_readfloatbe_offset.md | 21 +++ buffer/buf_readfloatle_offset.md | 4 +- buffer/buf_readint16be_offset.md | 23 +++ buffer/buf_readint16le_offset.md | 4 +- buffer/buf_readint32be_offset.md | 23 +++ buffer/buf_readint32le_offset.md | 4 +- buffer/buf_readintbe_offset_bytelength.md | 26 ++++ buffer/buf_readintle_offset_bytelength.md | 9 +- buffer/buf_readuint16be_offset.md | 23 +++ buffer/buf_readuint16le_offset.md | 6 +- buffer/buf_readuint32be_offset.md | 21 +++ buffer/buf_readuint32le_offset.md | 4 +- buffer/buf_readuintbe_offset_bytelength.md | 24 ++++ buffer/buf_readuintle_offset_bytelength.md | 7 +- buffer/buf_writebigint64be_value_offset.md | 23 +++ buffer/buf_writebigint64le_value_offset.md | 6 +- buffer/buf_writebiguint64be_value_offset.md | 21 +++ buffer/buf_writebiguint64le_value_offset.md | 3 +- buffer/buf_writedoublebe_value_offset.md | 26 ++++ buffer/buf_writedoublele_value_offset.md | 7 +- buffer/buf_writefloatbe_value_offset.md | 28 ++++ buffer/buf_writefloatle_value_offset.md | 7 +- buffer/buf_writeint16be_value_offset.md | 26 ++++ buffer/buf_writeint16le_value_offset.md | 9 +- buffer/buf_writeint32be_value_offset.md | 28 ++++ buffer/buf_writeint32le_value_offset.md | 9 +- .../buf_writeintbe_value_offset_bytelength.md | 28 ++++ .../buf_writeintle_value_offset_bytelength.md | 7 +- buffer/buf_writeuint16be_value_offset.md | 27 ++++ buffer/buf_writeuint16le_value_offset.md | 8 +- buffer/buf_writeuint32be_value_offset.md | 26 ++++ buffer/buf_writeuint32le_value_offset.md | 7 +- ...buf_writeuintbe_value_offset_bytelength.md | 27 ++++ ...buf_writeuintle_value_offset_bytelength.md | 7 +- buffer/buffer.md | 12 +- buffer/buffer_constants.md | 2 - buffer/buffer_inspect_max_bytes.md | 2 - buffer/buffer_kmaxlength.md | 2 - buffer/buffer_module_apis.md | 5 + .../buffer_transcode_source_fromenc_toenc.md | 2 - buffer/buffers_and_character_encodings.md | 1 + buffer/buffers_and_typedarrays.md | 29 ++-- child_process/child_process.md | 2 + ...d_process_exec_command_options_callback.md | 7 +- ...ess_execfile_file_args_options_callback.md | 2 +- ..._process_execfilesync_file_args_options.md | 2 +- .../child_process_execsync_command_options.md | 2 +- ...ld_process_fork_modulepath_args_options.md | 2 +- ...hild_process_spawn_command_args_options.md | 4 +- ..._process_spawnsync_command_args_options.md | 2 +- child_process/event_message.md | 2 +- .../example_sending_a_socket_object.md | 7 +- cli/enable_source_maps.md | 2 +- ...> max_old_space_size_size_in_megabytes.md} | 0 ...ir_directory_report_directory_directory.md | 2 +- cli/report_filename_filename.md | 2 +- cli/report_on_fatalerror.md | 2 +- cli/report_on_signal.md | 2 +- cli/report_signal_signal.md | 2 +- cli/report_uncaught_exception.md | 2 +- cli/source_map_cache.md | 4 +- cluster/cluster.md | 2 + cluster/cluster_settings.md | 2 +- console/console.md | 2 + crypto/crypto.md | 2 + crypto/crypto_constants.md | 2 +- crypto/node_js_crypto_constants.md | 1 + crypto/other_openssl_constants.md | 2 + .../v8_inspector_integration_for_node_js.md | 2 +- .../dep0085_asynchooks_sensitive_api.md | 2 +- .../dep0143_transform_transformstate.md | 121 +--------------- deprecations/dep0144_module_parent.md | 32 +++++ deprecations/dep0145_socket_buffersize.md | 133 ++++++++++++++++++ ...mple_ipv6_outgoing_multicast_interface.md} | 0 ...hip_multicastaddress_multicastinterface.md | 3 + dgram/socket_address.md | 2 + ...address_groupaddress_multicastinterface.md | 3 + dgram/socket_disconnect.md | 2 +- dgram/socket_getrecvbuffersize.md | 1 + dgram/socket_getsendbuffersize.md | 1 + dgram/socket_remoteaddress.md | 4 +- ...msg_offset_length_port_address_callback.md | 2 + dgram/socket_setbroadcast_flag.md | 2 + ...etmulticastinterface_multicastinterface.md | 2 + dgram/socket_setmulticastloopback_flag.md | 2 +- dgram/socket_setmulticastttl_ttl.md | 1 + dgram/socket_setrecvbuffersize_size.md | 2 + dgram/socket_setsendbuffersize_size.md | 2 + dgram/socket_setttl_ttl.md | 1 + dgram/udp_datagram_sockets.md | 2 + dns/dns.md | 2 + dns/dnspromises_setservers_servers.md | 2 +- dns/supported_getaddrinfo_flags.md | 2 +- domain/domain.md | 2 + domain/domains_and_promises.md | 4 +- errors/class_referenceerror.md | 2 +- errors/class_typeerror.md | 2 +- errors/err_entry_type_mismatch.md | 11 -- errors/err_falsy_value_rejection.md | 2 +- errors/err_feature_unavailable_on_platform.md | 5 +- errors/err_fs_watcher_already_started.md | 5 - errors/err_fs_watcher_not_started.md | 5 - errors/err_http2_already_shutdown.md | 4 - errors/err_http2_error_1.md | 4 - errors/err_invalid_repl_history.md | 5 - errors/err_invalid_repl_type.md | 6 - errors/err_out_of_range.md | 2 +- errors/err_package_import_not_defined.md | 5 + errors/err_stream_has_stringdecoder.md | 11 -- errors/err_string_too_large.md | 5 - errors/err_tty_writable_not_readable.md | 77 ---------- errors/err_zlib_binding_closed.md | 74 ++++++++++ errors/error_code.md | 2 +- errors/other_error_codes.md | 5 - esm/approach_1_use_an_es_module_wrapper.md | 2 +- esm/code_resolve_code_hook.md | 11 +- esm/commonjs_json_and_native_modules.md | 2 +- esm/conditional_exports.md | 34 +++-- esm/dual_commonjs_es_module_packages.md | 2 +- esm/import_statements.md | 2 +- esm/internal_package_imports.md | 36 +++++ esm/nested_conditions.md | 4 +- esm/package_entry_points.md | 2 +- esm/package_scope_and_file_extensions.md | 10 +- esm/resolver_algorithm.md | 122 +++++++++++----- ...iple_events_emitted_on_process_nexttick.md | 53 +++++++ events/event_listener.md | 2 +- events/events.md | 2 + events/events_once_emitter_name.md | 19 ++- .../node_js_eventtarget_vs_dom_eventtarget.md | 2 +- fs/class_fs_readstream.md | 2 +- fs/class_fs_writestream.md | 1 + fs/file_system.md | 9 +- fs/file_system_flags.md | 4 +- fs/fs_access_path_mode_callback.md | 2 +- fs/fs_accesssync_path_mode.md | 2 +- fs/fs_constants.md | 2 +- fs/fspromises_access_path_mode.md | 2 +- fs/stats_rdev.md | 2 +- http/http.md | 2 + http/http_get_url_options_callback.md | 1 + http/message_url.md | 7 +- http/new_agent_options.md | 7 + http2/class_http2stream.md | 12 ++ http2/compatibility_api.md | 2 +- http2/event_ready.md | 8 ++ http2/event_stream.md | 4 +- http2/event_stream_1.md | 2 +- http2/event_stream_2.md | 2 +- ...tesecureserver_options_onrequesthandler.md | 2 +- ...2_createserver_options_onrequesthandler.md | 2 +- ...stream_respondwithfd_fd_headers_options.md | 4 +- ...am_respondwithfile_path_headers_options.md | 6 +- http2/http_2.md | 2 + http2/request_url.md | 11 +- http2/response_setheader_name_value.md | 6 +- ...tehead_statuscode_statusmessage_headers.md | 6 +- http2/server_side_example.md | 2 +- https/https.md | 2 + inspector/inspector.md | 2 + modules/all_together.md | 13 +- modules/module_parent.md | 10 +- modules/new_sourcemap_payload.md | 2 +- ...cemap_findentry_linenumber_columnnumber.md | 2 + n-api/module_registration.md | 4 +- n-api/n_api.md | 2 +- n-api/n_api_callback_types.md | 1 + n-api/napi_add_finalizer.md | 1 + n-api/napi_async_complete_callback.md | 3 + n-api/napi_async_execute_callback.md | 10 +- n-api/napi_callback.md | 3 + n-api/napi_create_async_work.md | 3 +- n-api/napi_create_external.md | 2 +- n-api/napi_create_external_arraybuffer.md | 2 +- n-api/napi_create_external_buffer.md | 4 +- n-api/napi_create_function.md | 2 +- n-api/napi_create_threadsafe_function.md | 1 + n-api/napi_define_class.md | 4 +- n-api/napi_extended_error_info.md | 2 +- n-api/napi_finalize.md | 3 + n-api/napi_handle_scope.md | 2 +- n-api/napi_property_descriptor.md | 6 +- n-api/napi_ref.md | 2 +- n-api/napi_set_instance_data.md | 1 + n-api/napi_threadsafe_function_call_js.md | 3 + n-api/napi_unref_threadsafe_function.md | 4 + n-api/napi_wrap.md | 1 + n-api/prebuildify.md | 2 +- n-api/usage.md | 3 +- net/net.md | 2 + net/socket_buffersize.md | 4 + os/os.md | 2 + path/path.md | 2 + perf_hooks/performance_measurement_apis.md | 2 + process/event_message.md | 2 +- process/process.md | 2 + process/process_report.md | 2 +- process/process_report_directory.md | 2 +- process/process_report_filename.md | 2 +- process/process_report_getreport_err.md | 2 +- process/process_report_reportonsignal.md | 2 +- ...rocess_report_reportonuncaughtexception.md | 2 +- process/process_report_signal.md | 2 +- ...process_report_writereport_filename_err.md | 2 +- process/process_stdin.md | 16 +-- punycode/punycode.md | 2 + querystring/query_string.md | 2 + readline/readline.md | 2 + repl/repl.md | 2 + stream/api_for_stream_consumers.md | 2 +- stream/readable_read_size.md | 37 ++++- stream/readable_readableflowing.md | 2 +- stream/readable_unshift_chunk_encoding.md | 2 +- stream/stream.md | 2 + ..._source_transforms_destination_callback.md | 99 ------------- stream/stream_pipeline_streams_callback.md | 100 +++++++++++++ stream/transform_flush_callback.md | 2 +- ...sform_transform_chunk_encoding_callback.md | 4 +- string_decoder/string_decoder.md | 2 + ...{usage_example.md => usage_and_example.md} | 0 timers/timers.md | 2 + tls/perfect_forward_secrecy.md | 2 +- tls/session_identifiers.md | 20 +++ tls/session_resumption.md | 86 ----------- tls/session_tickets.md | 68 +++++++++ tls/tls_createsecurecontext_options.md | 7 +- ...server_options_secureconnectionlistener.md | 15 +- tls/tls_ssl.md | 2 + tls/tlssocket_getephemeralkeyinfo.md | 2 +- tracing/trace_events.md | 6 +- tty/tty.md | 2 + url/url.md | 2 + ...ring_parsequerystring_slashesdenotehost.md | 6 + util/util.md | 2 + ...n.md => util_debuglog_section_callback.md} | 17 +++ ..._inspect_object_showhidden_depth_colors.md | 7 + v8/v8.md | 2 + v8/v8_writeheapsnapshot_filename.md | 2 +- ...t_runinnewcontext_contextobject_options.md | 7 + ...ns_with_asynchronous_tasks_and_promises.md | 61 ++++++++ ...ss_nexttick_promises_and_queuemicrotask.md | 25 ---- vm/vm_createcontext_contextobject_options.md | 7 + vm/vm_executing_javascript.md | 2 + ...innewcontext_code_contextobject_options.md | 7 + wasi/wasi_initialize_instance.md | 16 +++ wasi/webassembly_system_interface_wasi.md | 2 + worker_threads/new_worker_filename_options.md | 10 ++ worker_threads/worker_threads.md | 2 + worker_threads/worker_unref.md | 2 + ...compressing_http_requests_and_responses.md | 2 +- zlib/zlib.md | 2 + 272 files changed, 1740 insertions(+), 857 deletions(-) create mode 100644 buffer/buffer_module_apis.md rename cli/{max_old_space_size_size_in_mbytes.md => max_old_space_size_size_in_megabytes.md} (100%) create mode 100644 deprecations/dep0144_module_parent.md create mode 100644 deprecations/dep0145_socket_buffersize.md rename dgram/{examples_ipv6_outgoing_multicast_interface.md => example_ipv6_outgoing_multicast_interface.md} (100%) delete mode 100644 errors/err_entry_type_mismatch.md delete mode 100644 errors/err_fs_watcher_already_started.md delete mode 100644 errors/err_fs_watcher_not_started.md delete mode 100644 errors/err_http2_already_shutdown.md delete mode 100644 errors/err_http2_error_1.md delete mode 100644 errors/err_invalid_repl_history.md delete mode 100644 errors/err_invalid_repl_type.md create mode 100644 errors/err_package_import_not_defined.md delete mode 100644 errors/err_stream_has_stringdecoder.md delete mode 100644 errors/err_string_too_large.md delete mode 100644 errors/err_tty_writable_not_readable.md delete mode 100644 errors/other_error_codes.md create mode 100644 esm/internal_package_imports.md create mode 100644 events/awaiting_multiple_events_emitted_on_process_nexttick.md create mode 100644 http2/event_ready.md create mode 100644 stream/stream_pipeline_streams_callback.md rename synopsis/{usage_example.md => usage_and_example.md} (100%) create mode 100644 tls/session_identifiers.md create mode 100644 tls/session_tickets.md rename util/{util_debuglog_section.md => util_debuglog_section_callback.md} (69%) create mode 100644 vm/timeout_interactions_with_asynchronous_tasks_and_promises.md delete mode 100644 vm/timeout_limitations_when_using_process_nexttick_promises_and_queuemicrotask.md create mode 100644 wasi/wasi_initialize_instance.md diff --git a/addons/callbacks.md b/addons/callbacks.md index 60a9e5c2..54c907c6 100644 --- a/addons/callbacks.md +++ b/addons/callbacks.md @@ -13,7 +13,6 @@ using v8::Function; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; -using v8::NewStringType; using v8::Null; using v8::Object; using v8::String; @@ -26,8 +25,7 @@ void RunCallback(const FunctionCallbackInfo& args) { const unsigned argc = 1; Local argv[argc] = { String::NewFromUtf8(isolate, - "hello world", - NewStringType::kNormal).ToLocalChecked() }; + "hello world").ToLocalChecked() }; cb->Call(context, Null(isolate), argc, argv).ToLocalChecked(); } diff --git a/addons/context_aware_addons.md b/addons/context_aware_addons.md index d8910c9f..89f48640 100644 --- a/addons/context_aware_addons.md +++ b/addons/context_aware_addons.md @@ -91,8 +91,7 @@ NODE_MODULE_INIT(/* exports, module, context */) { // 把 `Method` 方法暴露给 JavaScript, // 并确保其接收我们通过把 `external` 作为 `FunctionTemplate` 构造函数第三个参数时创建的每个插件实例的数据。 exports->Set(context, - String::NewFromUtf8(isolate, "method", NewStringType::kNormal) - .ToLocalChecked(), + String::NewFromUtf8(isolate, "method").ToLocalChecked(), FunctionTemplate::New(isolate, Method, external) ->GetFunction(context).ToLocalChecked()).FromJust(); } diff --git a/addons/factory_of_wrapped_objects.md b/addons/factory_of_wrapped_objects.md index 62573945..3d9746a2 100644 --- a/addons/factory_of_wrapped_objects.md +++ b/addons/factory_of_wrapped_objects.md @@ -88,7 +88,6 @@ using v8::FunctionTemplate; using v8::Global; using v8::Isolate; using v8::Local; -using v8::NewStringType; using v8::Number; using v8::Object; using v8::String; @@ -106,8 +105,7 @@ MyObject::~MyObject() { void MyObject::Init(Isolate* isolate) { // 准备构造函数模版 Local tpl = FunctionTemplate::New(isolate, New); - tpl->SetClassName(String::NewFromUtf8( - isolate, "MyObject", NewStringType::kNormal).ToLocalChecked()); + tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); // 原型 diff --git a/addons/function_arguments.md b/addons/function_arguments.md index 868df2df..9a14fb1c 100644 --- a/addons/function_arguments.md +++ b/addons/function_arguments.md @@ -14,7 +14,6 @@ using v8::Exception; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; -using v8::NewStringType; using v8::Number; using v8::Object; using v8::String; @@ -29,18 +28,16 @@ void Add(const FunctionCallbackInfo& args) { if (args.Length() < 2) { // 抛出一个错误并传回到 JavaScript。 isolate->ThrowException(Exception::TypeError( - String::NewFromUtf8(isolate, - "参数的数量错误", - NewStringType::kNormal).ToLocalChecked())); + String::NewFromUtf8(isolate, + "参数的数量错误").ToLocalChecked())); return; } // 检查参数的类型。 if (!args[0]->IsNumber() || !args[1]->IsNumber()) { isolate->ThrowException(Exception::TypeError( - String::NewFromUtf8(isolate, - "参数错误", - NewStringType::kNormal).ToLocalChecked())); + String::NewFromUtf8(isolate, + "参数错误").ToLocalChecked())); return; } diff --git a/addons/function_factory.md b/addons/function_factory.md index 787b66e0..cf7747c0 100644 --- a/addons/function_factory.md +++ b/addons/function_factory.md @@ -13,7 +13,6 @@ using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; -using v8::NewStringType; using v8::Object; using v8::String; using v8::Value; @@ -21,7 +20,7 @@ using v8::Value; void MyFunction(const FunctionCallbackInfo& args) { Isolate* isolate = args.GetIsolate(); args.GetReturnValue().Set(String::NewFromUtf8( - isolate, "hello world", NewStringType::kNormal).ToLocalChecked()); + isolate, "hello world").ToLocalChecked()); } void CreateFunction(const FunctionCallbackInfo& args) { @@ -33,7 +32,7 @@ void CreateFunction(const FunctionCallbackInfo& args) { // 可以省略这步使它匿名 fn->SetName(String::NewFromUtf8( - isolate, "theFunction", NewStringType::kNormal).ToLocalChecked()); + isolate, "theFunction").ToLocalChecked()); args.GetReturnValue().Set(fn); } diff --git a/addons/hello_world.md b/addons/hello_world.md index d55f8018..eb47cf9a 100644 --- a/addons/hello_world.md +++ b/addons/hello_world.md @@ -16,7 +16,6 @@ namespace demo { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; -using v8::NewStringType; using v8::Object; using v8::String; using v8::Value; @@ -24,7 +23,7 @@ using v8::Value; void Method(const FunctionCallbackInfo& args) { Isolate* isolate = args.GetIsolate(); args.GetReturnValue().Set(String::NewFromUtf8( - isolate, "world", NewStringType::kNormal).ToLocalChecked()); + isolate, "world").ToLocalChecked()); } void Initialize(Local exports) { diff --git a/addons/object_factory.md b/addons/object_factory.md index 14a26856..e2296417 100644 --- a/addons/object_factory.md +++ b/addons/object_factory.md @@ -12,7 +12,6 @@ using v8::Context; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; -using v8::NewStringType; using v8::Object; using v8::String; using v8::Value; @@ -24,8 +23,7 @@ void CreateObject(const FunctionCallbackInfo& args) { Local obj = Object::New(isolate); obj->Set(context, String::NewFromUtf8(isolate, - "msg", - NewStringType::kNormal).ToLocalChecked(), + "msg").ToLocalChecked(), args[0]->ToString(context).ToLocalChecked()) .FromJust(); diff --git a/addons/passing_wrapped_objects_around.md b/addons/passing_wrapped_objects_around.md index d9d8605b..1606df45 100644 --- a/addons/passing_wrapped_objects_around.md +++ b/addons/passing_wrapped_objects_around.md @@ -97,7 +97,6 @@ using v8::FunctionTemplate; using v8::Global; using v8::Isolate; using v8::Local; -using v8::NewStringType; using v8::Object; using v8::String; using v8::Value; @@ -114,8 +113,7 @@ MyObject::~MyObject() { void MyObject::Init(Isolate* isolate) { // Prepare constructor template Local tpl = FunctionTemplate::New(isolate, New); - tpl->SetClassName(String::NewFromUtf8( - isolate, "MyObject", NewStringType::kNormal).ToLocalChecked()); + tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Local context = isolate->GetCurrentContext(); diff --git a/addons/wrapping_c_objects.md b/addons/wrapping_c_objects.md index 5e8f0621..2c8e0577 100644 --- a/addons/wrapping_c_objects.md +++ b/addons/wrapping_c_objects.md @@ -67,7 +67,6 @@ using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; -using v8::NewStringType; using v8::Number; using v8::Object; using v8::ObjectTemplate; @@ -91,8 +90,7 @@ void MyObject::Init(Local exports) { // 准备构造函数模版 Local tpl = FunctionTemplate::New(isolate, New, addon_data); - tpl->SetClassName(String::NewFromUtf8( - isolate, "MyObject", NewStringType::kNormal).ToLocalChecked()); + tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); // 原型 @@ -101,8 +99,8 @@ void MyObject::Init(Local exports) { Local constructor = tpl->GetFunction(context).ToLocalChecked(); addon_data->SetInternalField(0, constructor); exports->Set(context, String::NewFromUtf8( - isolate, "MyObject", NewStringType::kNormal).ToLocalChecked(), - constructor).FromJust(); + isolate, "MyObject").ToLocalChecked(), + constructor).FromJust(); } void MyObject::New(const FunctionCallbackInfo& args) { diff --git a/assert/assert.md b/assert/assert.md index f151d545..3567d06e 100644 --- a/assert/assert.md +++ b/assert/assert.md @@ -3,5 +3,7 @@ > 稳定性: 2 - 稳定 + + `assert` 模块提供了一组断言函数,用于验证不变量。 diff --git a/async_hooks/async_hooks.md b/async_hooks/async_hooks.md index 591788ba..4e3472ad 100644 --- a/async_hooks/async_hooks.md +++ b/async_hooks/async_hooks.md @@ -3,6 +3,8 @@ > Stability: 1 - Experimental + + The `async_hooks` module provides an API to track asynchronous resources. It can be accessed using: diff --git a/async_hooks/asynchronous_context_example.md b/async_hooks/asynchronous_context_example.md index 52a31466..25675206 100644 --- a/async_hooks/asynchronous_context_example.md +++ b/async_hooks/asynchronous_context_example.md @@ -17,20 +17,17 @@ async_hooks.createHook({ }, before(asyncId) { const indentStr = ' '.repeat(indent); - fs.writeFileSync('log.out', - `${indentStr}before: ${asyncId}\n`, { flag: 'a' }); + fs.writeSync(process.stdout.fd, `${indentStr}before: ${asyncId}\n`); indent += 2; }, after(asyncId) { indent -= 2; const indentStr = ' '.repeat(indent); - fs.writeFileSync('log.out', - `${indentStr}after: ${asyncId}\n`, { flag: 'a' }); + fs.writeSync(process.stdout.fd, `${indentStr}after: ${asyncId}\n`); }, destroy(asyncId) { const indentStr = ' '.repeat(indent); - fs.writeFileSync('log.out', - `${indentStr}destroy: ${asyncId}\n`, { flag: 'a' }); + fs.writeSync(process.stdout.fd, `${indentStr}destroy: ${asyncId}\n`); }, }).enable(); @@ -66,14 +63,36 @@ the value of the current execution context; which is delineated by calls to Only using `execution` to graph resource allocation results in the following: ```console -Timeout(7) -> TickObject(6) -> root(1) + root(1) + ^ + | +TickObject(6) + ^ + | + Timeout(7) ``` The `TCPSERVERWRAP` is not part of this graph, even though it was the reason for `console.log()` being called. This is because binding to a port without a host name is a *synchronous* operation, but to maintain a completely asynchronous -API the user's callback is placed in a `process.nextTick()`. +API the user's callback is placed in a `process.nextTick()`. Which is why +`TickObject` is present in the output and is a 'parent' for `.listen()` +callback. The graph only shows *when* a resource was created, not *why*, so to track -the *why* use `triggerAsyncId`. +the *why* use `triggerAsyncId`. Which can be represented with the following +graph: + +```console + bootstrap(1) + | + ˅ +TCPSERVERWRAP(5) + | + ˅ + TickObject(6) + | + ˅ + Timeout(7) +``` diff --git a/async_hooks/resource.md b/async_hooks/resource.md index d7e72916..28c3de4d 100644 --- a/async_hooks/resource.md +++ b/async_hooks/resource.md @@ -4,7 +4,7 @@ been initialized. This can contain useful information that can vary based on the value of `type`. For instance, for the `GETADDRINFOREQWRAP` resource type, `resource` provides the host name used when looking up the IP address for the host in `net.Server.listen()`. The API for accessing this information is -currently not considered public, but using the Embedder API, users can provide +not supported, but using the Embedder API, users can provide and document their own resource objects. For example, such a resource object could contain the SQL query being executed. diff --git a/buffer/buf_byteoffset.md b/buffer/buf_byteoffset.md index 9685e834..bc372cb6 100644 --- a/buffer/buf_byteoffset.md +++ b/buffer/buf_byteoffset.md @@ -1,9 +1,9 @@ -* {integer} 创建 `Buffer` 对象时基于的底层 `ArrayBuffer` 对象的 `byteOffset`。 +* {integer} `Buffer` 底层的 `ArrayBuffer` 对象的 `byteOffset`。 -当 `Buffer.from(ArrayBuffer, byteOffset, length)` 设置了 `byteOffset` 或创建一个小于 `Buffer.poolSize` 的 buffer 时,底层的 `ArrayBuffer` 的偏移量并不是从 0 开始。 +当 `Buffer.from(ArrayBuffer, byteOffset, length)` 设置了 `byteOffset` 或创建一个小于 `Buffer.poolSize` 的 `Buffer` 时,底层的 `ArrayBuffer` 的偏移量并不是从 0 开始。 -当直接使用 `buf.buffer` 访问底层的 `ArrayBuffer` 时可能会导致问题,因为 `ArrayBuffer` 的其他部分可能并不指向 `buf` 对象。 +当直接使用 `buf.buffer` 访问底层的 `ArrayBuffer` 时可能会导致问题,因为 `ArrayBuffer` 的其他部分可能并不指向 `Buffer` 对象。 当创建与 `Buffer` 共享其内存的 `TypedArray` 对象时,需要正确地指定 `byteOffset`。 diff --git a/buffer/buf_index.md b/buffer/buf_index.md index 22570687..a8e9e2c5 100644 --- a/buffer/buf_index.md +++ b/buffer/buf_index.md @@ -9,7 +9,7 @@ name: [index] 该值指向单个字节,所以有效的值的范围是 `0x00` 至 `0xFF`(十六进制)、或 `0` 至 `255`(十进制)。 该操作符继承自 `Uint8Array`,所以对越界访问的行为与 `Uint8Array` 相同。 -也就是说,当 `index` 为负数或 `>= buf.length` 时,则 `buf[index]` 返回 `undefined`,而如果 `index` 为负数或 `>= buf.length` 时,则 `buf[index] = value` 不会修改该 buffer。 +也就是说,当 `index` 为负数或大于或等于 `buf.length` 时,则 `buf[index]` 返回 `undefined`,而如果 `index` 为负数或 `>= buf.length` 时,则 `buf[index] = value` 不会修改该 buffer。 ```js // 拷贝 ASCII 字符串到 `Buffer`,每次拷贝一个字节。 diff --git a/buffer/buf_readbigint64be_offset.md b/buffer/buf_readbigint64be_offset.md index e69de29b..1794a22b 100644 --- a/buffer/buf_readbigint64be_offset.md +++ b/buffer/buf_readbigint64be_offset.md @@ -0,0 +1,13 @@ + + +* `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 +* 返回: {bigint} + +从 `buf` 中指定的 `offset` 读取一个有符号大端序的 64 位整数值。 + +从 `Buffer` 中读取的整数值会被解析为二进制补码值。 + diff --git a/buffer/buf_readbigint64le_offset.md b/buffer/buf_readbigint64le_offset.md index ac735bd0..ab234602 100644 --- a/buffer/buf_readbigint64le_offset.md +++ b/buffer/buf_readbigint64le_offset.md @@ -7,7 +7,7 @@ added: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 * 返回: {bigint} -用指定的[字节序][endianness](`readBigInt64BE()` 读取为大端序,`readBigInt64LE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个有符号的 64 位整数值。 +从 `buf` 中指定的 `offset` 读取一个有符号小端序的 64 位整数值。 从 `Buffer` 中读取的整数值会被解析为二进制补码值。 diff --git a/buffer/buf_readbiguint64be_offset.md b/buffer/buf_readbiguint64be_offset.md index e69de29b..4ad34a4e 100644 --- a/buffer/buf_readbiguint64be_offset.md +++ b/buffer/buf_readbiguint64be_offset.md @@ -0,0 +1,18 @@ + + +* `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 +* 返回: {bigint} + +从 `buf` 中指定的 `offset` 读取一个无符号大端序的 64 位整数值。 + +```js +const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + +console.log(buf.readBigUInt64BE(0)); +// 打印: 4294967295n +``` + diff --git a/buffer/buf_readbiguint64le_offset.md b/buffer/buf_readbiguint64le_offset.md index cf80224e..f4a58a49 100644 --- a/buffer/buf_readbiguint64le_offset.md +++ b/buffer/buf_readbiguint64le_offset.md @@ -7,14 +7,11 @@ added: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 * 返回: {bigint} -用指定的[字节序][endianness](`readBigUInt64BE()` 读取为大端序,`readBigUInt64LE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个无符号的 64 位整数值。 +从 `buf` 中指定的 `offset` 读取一个无符号小端序的 64 位整数值。 ```js const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); -console.log(buf.readBigUInt64BE(0)); -// 打印: 4294967295n - console.log(buf.readBigUInt64LE(0)); // 打印: 18446744069414584320n ``` diff --git a/buffer/buf_readdoublebe_offset.md b/buffer/buf_readdoublebe_offset.md index e69de29b..924bad03 100644 --- a/buffer/buf_readdoublebe_offset.md +++ b/buffer/buf_readdoublebe_offset.md @@ -0,0 +1,21 @@ + + +* `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 +* 返回: {number} + +从 `buf` 中指定的 `offset` 读取一个 64 位的大端序双精度值。 + +```js +const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + +console.log(buf.readDoubleBE(0)); +// 打印: 8.20788039913184e-304 +``` + diff --git a/buffer/buf_readdoublele_offset.md b/buffer/buf_readdoublele_offset.md index 8aaabbc6..88f29000 100644 --- a/buffer/buf_readdoublele_offset.md +++ b/buffer/buf_readdoublele_offset.md @@ -10,13 +10,11 @@ changes: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 * 返回: {number} -用指定的[字节序][endianness](`readDoubleBE()` 读取为大端序,`readDoubleLE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个 64 位双精度值。 +从 `buf` 中指定的 `offset` 读取一个 64 位的小端序双精度值。 ```js const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); -console.log(buf.readDoubleBE(0)); -// 打印: 8.20788039913184e-304 console.log(buf.readDoubleLE(0)); // 打印: 5.447603722011605e-270 console.log(buf.readDoubleLE(1)); diff --git a/buffer/buf_readfloatbe_offset.md b/buffer/buf_readfloatbe_offset.md index e69de29b..de941729 100644 --- a/buffer/buf_readfloatbe_offset.md +++ b/buffer/buf_readfloatbe_offset.md @@ -0,0 +1,21 @@ + + +* `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 +* 返回: {number} + +从 `buf` 中指定的 `offset` 读取一个 32 位的大端序浮点值。 + +```js +const buf = Buffer.from([1, 2, 3, 4]); + +console.log(buf.readFloatBE(0)); +// 打印: 2.387939260590663e-38 +``` + diff --git a/buffer/buf_readfloatle_offset.md b/buffer/buf_readfloatle_offset.md index d1fc12b0..629ced58 100644 --- a/buffer/buf_readfloatle_offset.md +++ b/buffer/buf_readfloatle_offset.md @@ -10,13 +10,11 @@ changes: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 * 返回: {number} -用指定的[字节序][endianness](`readFloatBE()` 读取为大端序,`readFloatLE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个 32 位浮点值。 +从 `buf` 中指定的 `offset` 读取一个 32 位的小端序浮点值。 ```js const buf = Buffer.from([1, 2, 3, 4]); -console.log(buf.readFloatBE(0)); -// 打印: 2.387939260590663e-38 console.log(buf.readFloatLE(0)); // 打印: 1.539989614439558e-36 console.log(buf.readFloatLE(1)); diff --git a/buffer/buf_readint16be_offset.md b/buffer/buf_readint16be_offset.md index e69de29b..29c50ebe 100644 --- a/buffer/buf_readint16be_offset.md +++ b/buffer/buf_readint16be_offset.md @@ -0,0 +1,23 @@ + + +* `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 2`。**默认值:** `0`。 +* 返回: {integer} + +从 `buf` 中指定的 `offset` 读取一个有符号大端序的 16 位整数值。 + +从 `Buffer` 中读取的整数值会被解析为二进制补码值。 + +```js +const buf = Buffer.from([0, 5]); + +console.log(buf.readInt16BE(0)); +// 打印: 5 +``` + diff --git a/buffer/buf_readint16le_offset.md b/buffer/buf_readint16le_offset.md index 2ebe5df4..e37d9547 100644 --- a/buffer/buf_readint16le_offset.md +++ b/buffer/buf_readint16le_offset.md @@ -10,15 +10,13 @@ changes: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 2`。**默认值:** `0`。 * 返回: {integer} -用指定的[字节序][endianness](`readInt16BE()` 读取为大端序,`readInt16LE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个有符号的 16 位整数值。 +从 `buf` 中指定的 `offset` 读取一个有符号小端序的 16 位整数值。 从 `Buffer` 中读取的整数值会被解析为二进制补码值。 ```js const buf = Buffer.from([0, 5]); -console.log(buf.readInt16BE(0)); -// 打印: 5 console.log(buf.readInt16LE(0)); // 打印: 1280 console.log(buf.readInt16LE(1)); diff --git a/buffer/buf_readint32be_offset.md b/buffer/buf_readint32be_offset.md index e69de29b..08dd6ab4 100644 --- a/buffer/buf_readint32be_offset.md +++ b/buffer/buf_readint32be_offset.md @@ -0,0 +1,23 @@ + + +* `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 +* 返回: {integer} + +从 `buf` 中指定的 `offset` 读取一个有符号大端序的 32 位整数值。 + +从 `Buffer` 中读取的整数值会被解析为二进制补码值。 + +```js +const buf = Buffer.from([0, 0, 0, 5]); + +console.log(buf.readInt32BE(0)); +// 打印: 5 +``` + diff --git a/buffer/buf_readint32le_offset.md b/buffer/buf_readint32le_offset.md index fe1c1830..dbae308f 100644 --- a/buffer/buf_readint32le_offset.md +++ b/buffer/buf_readint32le_offset.md @@ -10,15 +10,13 @@ changes: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 * 返回: {integer} -用指定的[字节序][endianness](`readInt32BE()` 读取为大端序,`readInt32LE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个有符号的 32 位整数值。 +从 `buf` 中指定的 `offset` 读取一个有符号小端序的 32 位整数值。 从 `Buffer` 中读取的整数值会被解析为二进制补码值。 ```js const buf = Buffer.from([0, 0, 0, 5]); -console.log(buf.readInt32BE(0)); -// 打印: 5 console.log(buf.readInt32LE(0)); // 打印: 83886080 console.log(buf.readInt32LE(1)); diff --git a/buffer/buf_readintbe_offset_bytelength.md b/buffer/buf_readintbe_offset_bytelength.md index e69de29b..ad831c7e 100644 --- a/buffer/buf_readintbe_offset_bytelength.md +++ b/buffer/buf_readintbe_offset_bytelength.md @@ -0,0 +1,26 @@ + + +* `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - byteLength`。 +* `byteLength` {integer} 要读取的字节数。必须满足:`0 < byteLength <= 6`。 +* 返回: {integer} + +从 `buf` 中指定的 `offset` 读取 `byteLength` 个字节,并将读取的值解析为大端序的二进制补码值,最高支持 48 位精度。 + +```js +const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + +console.log(buf.readIntBE(0, 6).toString(16)); +// 打印: 1234567890ab +console.log(buf.readIntBE(1, 6).toString(16)); +// 抛出异常 ERR_OUT_OF_RANGE。 +console.log(buf.readIntBE(1, 0).toString(16)); +// 抛出异常 ERR_OUT_OF_RANGE。 +``` + diff --git a/buffer/buf_readintle_offset_bytelength.md b/buffer/buf_readintle_offset_bytelength.md index 4df2dfee..360e095d 100644 --- a/buffer/buf_readintle_offset_bytelength.md +++ b/buffer/buf_readintle_offset_bytelength.md @@ -11,19 +11,12 @@ changes: * `byteLength` {integer} 要读取的字节数。必须满足:`0 < byteLength <= 6`。 * 返回: {integer} -从 `buf` 中指定的 `offset` 读取 `byteLength` 个字节,并将读取的值解析为二进制补码值。 -最高支持 48 位精度。 +从 `buf` 中指定的 `offset` 读取 `byteLength` 个字节,并将读取的值解析为小端序的二进制补码值,最高支持 48 位精度。 ```js const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); console.log(buf.readIntLE(0, 6).toString(16)); // 打印: -546f87a9cbee -console.log(buf.readIntBE(0, 6).toString(16)); -// 打印: 1234567890ab -console.log(buf.readIntBE(1, 6).toString(16)); -// 抛出异常 ERR_OUT_OF_RANGE。 -console.log(buf.readIntBE(1, 0).toString(16)); -// 抛出异常 ERR_OUT_OF_RANGE。 ``` diff --git a/buffer/buf_readuint16be_offset.md b/buffer/buf_readuint16be_offset.md index e69de29b..711491ac 100644 --- a/buffer/buf_readuint16be_offset.md +++ b/buffer/buf_readuint16be_offset.md @@ -0,0 +1,23 @@ + + +* `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 2`。**默认值:** `0`。 +* 返回: {integer} + +从 `buf` 中指定的 `offset` 读取一个无符号大端序的 16 位整数值。 + +```js +const buf = Buffer.from([0x12, 0x34, 0x56]); + +console.log(buf.readUInt16BE(0).toString(16)); +// 打印: 1234 +console.log(buf.readUInt16BE(1).toString(16)); +// 打印: 3456 +``` + diff --git a/buffer/buf_readuint16le_offset.md b/buffer/buf_readuint16le_offset.md index 503be0fb..8a037e57 100644 --- a/buffer/buf_readuint16le_offset.md +++ b/buffer/buf_readuint16le_offset.md @@ -10,17 +10,13 @@ changes: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 2`。**默认值:** `0`。 * 返回: {integer} -用指定的[字节序][endianness](`readUInt16BE()` 读取为大端序,`readUInt16LE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个无符号的 16 位整数值。 +从 `buf` 中指定的 `offset` 读取一个无符号小端序的 16 位整数值。 ```js const buf = Buffer.from([0x12, 0x34, 0x56]); -console.log(buf.readUInt16BE(0).toString(16)); -// 打印: 1234 console.log(buf.readUInt16LE(0).toString(16)); // 打印: 3412 -console.log(buf.readUInt16BE(1).toString(16)); -// 打印: 3456 console.log(buf.readUInt16LE(1).toString(16)); // 打印: 5634 console.log(buf.readUInt16LE(2).toString(16)); diff --git a/buffer/buf_readuint32be_offset.md b/buffer/buf_readuint32be_offset.md index e69de29b..cdb434b9 100644 --- a/buffer/buf_readuint32be_offset.md +++ b/buffer/buf_readuint32be_offset.md @@ -0,0 +1,21 @@ + + +* `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 +* 返回: {integer} + +从 `buf` 中指定的 `offset` 读取一个无符号大端序的 32 位整数值。 + +```js +const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + +console.log(buf.readUInt32BE(0).toString(16)); +// 打印: 12345678 +``` + diff --git a/buffer/buf_readuint32le_offset.md b/buffer/buf_readuint32le_offset.md index bb3732f1..a3732a47 100644 --- a/buffer/buf_readuint32le_offset.md +++ b/buffer/buf_readuint32le_offset.md @@ -10,13 +10,11 @@ changes: * `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 * 返回: {integer} -用指定的[字节序][endianness](`readUInt32BE()` 读取为大端序,`readUInt32LE()` 读取为小端序)从 `buf` 中指定的 `offset` 读取一个无符号的 32 位整数值。 +从 `buf` 中指定的 `offset` 读取一个无符号小端序的 32 位整数值。 ```js const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); -console.log(buf.readUInt32BE(0).toString(16)); -// 打印: 12345678 console.log(buf.readUInt32LE(0).toString(16)); // 打印: 78563412 console.log(buf.readUInt32LE(1).toString(16)); diff --git a/buffer/buf_readuintbe_offset_bytelength.md b/buffer/buf_readuintbe_offset_bytelength.md index e69de29b..7515a26c 100644 --- a/buffer/buf_readuintbe_offset_bytelength.md +++ b/buffer/buf_readuintbe_offset_bytelength.md @@ -0,0 +1,24 @@ + + +* `offset` {integer} 开始读取之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - byteLength`。 +* `byteLength` {integer} 要读取的字节数。必须满足:`0 < byteLength <= 6`。 +* 返回: {integer} + +从 `buf` 中指定的 `offset` 读取 `byteLength` 个字节,并将读取的值解析为无符号大端序的整数,最高支持 48 位精度。 + +```js +const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + +console.log(buf.readUIntBE(0, 6).toString(16)); +// 打印: 1234567890ab +console.log(buf.readUIntBE(1, 6).toString(16)); +// 抛出异常 ERR_OUT_OF_RANGE。 +``` + diff --git a/buffer/buf_readuintle_offset_bytelength.md b/buffer/buf_readuintle_offset_bytelength.md index adb77fd2..92fdc546 100644 --- a/buffer/buf_readuintle_offset_bytelength.md +++ b/buffer/buf_readuintle_offset_bytelength.md @@ -11,17 +11,12 @@ changes: * `byteLength` {integer} 要读取的字节数。必须满足:`0 < byteLength <= 6`。 * 返回: {integer} -从 `buf` 中指定的 `offset` 读取 `byteLength` 个字节,并将读取的值解析为无符号的整数。 -最高支持 48 位精度。 +从 `buf` 中指定的 `offset` 读取 `byteLength` 个字节,并将读取的值解析为无符号小端序的整数,最高支持 48 位精度。 ```js const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); -console.log(buf.readUIntBE(0, 6).toString(16)); -// 打印: 1234567890ab console.log(buf.readUIntLE(0, 6).toString(16)); // 打印: ab9078563412 -console.log(buf.readUIntBE(1, 6).toString(16)); -//抛出异常 ERR_OUT_OF_RANGE。 ``` diff --git a/buffer/buf_writebigint64be_value_offset.md b/buffer/buf_writebigint64be_value_offset.md index e69de29b..0388e16f 100644 --- a/buffer/buf_writebigint64be_value_offset.md +++ b/buffer/buf_writebigint64be_value_offset.md @@ -0,0 +1,23 @@ + + +* `value` {bigint} 要写入 `buf` 的数值。 +* `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 +* 返回: {integer} `offset` 加上已写入的字节数。 + +将 `value` 作为大端序写入到 `buf` 中指定的 `offset` 位置。 + +`value` 会被解析并写入为二进制补码的有符号整数。 + +```js +const buf = Buffer.allocUnsafe(8); + +buf.writeBigInt64BE(0x0102030405060708n, 0); + +console.log(buf); +// 打印: +``` + diff --git a/buffer/buf_writebigint64le_value_offset.md b/buffer/buf_writebigint64le_value_offset.md index 0e9fe74d..d2d56359 100644 --- a/buffer/buf_writebigint64le_value_offset.md +++ b/buffer/buf_writebigint64le_value_offset.md @@ -8,16 +8,16 @@ added: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的[字节序][endianness](`writeBigInt64BE()` 写入为大端序,`writeBigInt64LE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +将 `value` 作为小端序写入到 `buf` 中指定的 `offset` 位置。 `value` 会被解析并写入为二进制补码的有符号整数。 ```js const buf = Buffer.allocUnsafe(8); -buf.writeBigInt64BE(0x0102030405060708n, 0); +buf.writeBigInt64LE(0x0102030405060708n, 0); console.log(buf); -// 打印: +// 打印: ``` diff --git a/buffer/buf_writebiguint64be_value_offset.md b/buffer/buf_writebiguint64be_value_offset.md index e69de29b..1d0cc9ee 100644 --- a/buffer/buf_writebiguint64be_value_offset.md +++ b/buffer/buf_writebiguint64be_value_offset.md @@ -0,0 +1,21 @@ + + +* `value` {bigint} 要写入 `buf` 的数值。 +* `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 +* 返回: {integer} `offset` 加上已写入的字节数。 + +将 `value` 作为大端序写入到 `buf` 中指定的 `offset` 位置。 + +```js +const buf = Buffer.allocUnsafe(8); + +buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + +console.log(buf); +// 打印: +``` + diff --git a/buffer/buf_writebiguint64le_value_offset.md b/buffer/buf_writebiguint64le_value_offset.md index 14ce6362..e93e65e3 100644 --- a/buffer/buf_writebiguint64le_value_offset.md +++ b/buffer/buf_writebiguint64le_value_offset.md @@ -8,8 +8,7 @@ added: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的[字节序][endianness](`writeBigUInt64BE()` 写入为大端序,`writeBigUInt64LE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 - +将 `value` 作为小端序写入到 `buf` 中指定的 `offset` 位置。 ```js const buf = Buffer.allocUnsafe(8); diff --git a/buffer/buf_writedoublebe_value_offset.md b/buffer/buf_writedoublebe_value_offset.md index e69de29b..80280c6b 100644 --- a/buffer/buf_writedoublebe_value_offset.md +++ b/buffer/buf_writedoublebe_value_offset.md @@ -0,0 +1,26 @@ + + +* `value` {number} 要写入 `buf` 的数值。 +* `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 +* 返回: {integer} `offset` 加上已写入的字节数。 + +将 `value` 作为大端序写入到 `buf` 中指定的 `offset` 位置。 +`value` 必须是 JavaScript 数值。 +当 `value` 不是 JavaScript 数值时,行为是未定义的。 + +```js +const buf = Buffer.allocUnsafe(8); + +buf.writeDoubleBE(123.456, 0); + +console.log(buf); +// 打印: +``` + diff --git a/buffer/buf_writedoublele_value_offset.md b/buffer/buf_writedoublele_value_offset.md index 90b94655..bec878f9 100644 --- a/buffer/buf_writedoublele_value_offset.md +++ b/buffer/buf_writedoublele_value_offset.md @@ -11,18 +11,13 @@ changes: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 8`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的[字节序][endianness](`writeDoubleBE()` 写入为大端序,`writeDoubleLE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +将 `value` 作为小端序写入到 `buf` 中指定的 `offset` 位置。 `value` 必须是 JavaScript 数值。 当 `value` 不是 JavaScript 数值时,行为是未定义的。 ```js const buf = Buffer.allocUnsafe(8); -buf.writeDoubleBE(123.456, 0); - -console.log(buf); -// 打印: - buf.writeDoubleLE(123.456, 0); console.log(buf); diff --git a/buffer/buf_writefloatbe_value_offset.md b/buffer/buf_writefloatbe_value_offset.md index e69de29b..80e44506 100644 --- a/buffer/buf_writefloatbe_value_offset.md +++ b/buffer/buf_writefloatbe_value_offset.md @@ -0,0 +1,28 @@ + + + +* `value` {number} 要写入 `buf` 的数值。 +* `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 +* 返回: {integer} `offset` 加上已写入的字节数。 + +将 `value` 作为大端序写入到 `buf` 中指定的 `offset` 位置。 +`value` 必须是 JavaScript 数值。 +当 `value` 不是 JavaScript 数值时,行为是未定义的。 + +```js +const buf = Buffer.allocUnsafe(4); + +buf.writeFloatBE(0xcafebabe, 0); + +console.log(buf); +// 打印: + +``` + diff --git a/buffer/buf_writefloatle_value_offset.md b/buffer/buf_writefloatle_value_offset.md index f1d96a9f..60531573 100644 --- a/buffer/buf_writefloatle_value_offset.md +++ b/buffer/buf_writefloatle_value_offset.md @@ -12,18 +12,13 @@ changes: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的[字节序][endianness](`writeFloatBE()` 写入为大端序,`writeFloatLE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +将 `value` 作为小端序写入到 `buf` 中指定的 `offset` 位置。 `value` 必须是 JavaScript 数值。 当 `value` 不是 JavaScript 数值时,行为是未定义的。 ```js const buf = Buffer.allocUnsafe(4); -buf.writeFloatBE(0xcafebabe, 0); - -console.log(buf); -// 打印: - buf.writeFloatLE(0xcafebabe, 0); console.log(buf); diff --git a/buffer/buf_writeint16be_value_offset.md b/buffer/buf_writeint16be_value_offset.md index e69de29b..d2ff9112 100644 --- a/buffer/buf_writeint16be_value_offset.md +++ b/buffer/buf_writeint16be_value_offset.md @@ -0,0 +1,26 @@ + + +* `value` {integer} 要写入 `buf` 的数值。 +* `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 2`。**默认值:** `0`。 +* 返回: {integer} `offset` 加上已写入的字节数。 + +将 `value` 作为大端序写入到 `buf` 中指定的 `offset` 位置。 +`value` 必须是有符号的 16 位整数。 +当 `value` 不是有符号的 16 位整数时,行为是未定义的。 + +```js +const buf = Buffer.allocUnsafe(2); + +buf.writeInt16BE(0x0102, 0); + +console.log(buf); +// 打印: +``` + diff --git a/buffer/buf_writeint16le_value_offset.md b/buffer/buf_writeint16le_value_offset.md index c9cf30b5..63c687a3 100644 --- a/buffer/buf_writeint16le_value_offset.md +++ b/buffer/buf_writeint16le_value_offset.md @@ -11,17 +11,16 @@ changes: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 2`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的[字节序][endianness](`writeInt16BE()` 写入为大端序,`writeInt16LE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +将 `value` 作为小端序写入到 `buf` 中指定的 `offset` 位置。 `value` 必须是有符号的 16 位整数。 当 `value` 不是有符号的 16 位整数时,行为是未定义的。 ```js -const buf = Buffer.allocUnsafe(4); +const buf = Buffer.allocUnsafe(2); -buf.writeInt16BE(0x0102, 0); -buf.writeInt16LE(0x0304, 2); +buf.writeInt16LE(0x0304, 0); console.log(buf); -// 打印: +// 打印: ``` diff --git a/buffer/buf_writeint32be_value_offset.md b/buffer/buf_writeint32be_value_offset.md index e69de29b..bfa379e9 100644 --- a/buffer/buf_writeint32be_value_offset.md +++ b/buffer/buf_writeint32be_value_offset.md @@ -0,0 +1,28 @@ + + +* `value` {integer} 要写入 `buf` 的数值。 +* `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 +* 返回: {integer} `offset` 加上已写入的字节数。 + +将 `value` 作为大端序写入到 `buf` 中指定的 `offset` 位置。 +`value` 必须是有符号的 32 位整数。 +当 `value` 不是有符号的 32 位整数,行为是未定义的。 + +`value` 会被解析并写入为二进制补码的有符号整数。 + +```js +const buf = Buffer.allocUnsafe(4); + +buf.writeInt32BE(0x01020304, 0); + +console.log(buf); +// 打印: +``` + diff --git a/buffer/buf_writeint32le_value_offset.md b/buffer/buf_writeint32le_value_offset.md index e36cddc3..5d7913b8 100644 --- a/buffer/buf_writeint32le_value_offset.md +++ b/buffer/buf_writeint32le_value_offset.md @@ -11,19 +11,18 @@ changes: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的[字节序][endianness](`writeInt32BE()` 写入为大端序,`writeInt32LE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +将 `value` 作为小端序写入到 `buf` 中指定的 `offset` 位置。 `value` 必须是有符号的 32 位整数。 当 `value` 不是有符号的 32 位整数,行为是未定义的。 `value` 会被解析并写入为二进制补码的有符号整数。 ```js -const buf = Buffer.allocUnsafe(8); +const buf = Buffer.allocUnsafe(4); -buf.writeInt32BE(0x01020304, 0); -buf.writeInt32LE(0x05060708, 4); +buf.writeInt32LE(0x05060708, 0); console.log(buf); -// 打印: +// 打印: ``` diff --git a/buffer/buf_writeintbe_value_offset_bytelength.md b/buffer/buf_writeintbe_value_offset_bytelength.md index e69de29b..521d98d5 100644 --- a/buffer/buf_writeintbe_value_offset_bytelength.md +++ b/buffer/buf_writeintbe_value_offset_bytelength.md @@ -0,0 +1,28 @@ + + +* `value` {integer} 要写入 `buf` 的数值。 +* `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - byteLength`。 +* `byteLength` {integer} 要写入的字节数。必须满足:`0 < byteLength <= 6`。 +* 返回: {integer} `offset` 加上已写入的字节数。 + +将 `value` 中的 `byteLength` 个字节作为大端序写入到 `buf` 中指定的 `offset` 位置。 +最高支持 48 位精度。 +当 `value` 不是有符号的整数时,行为是未定义的。 + +```js +const buf = Buffer.allocUnsafe(6); + +buf.writeIntBE(0x1234567890ab, 0, 6); + +console.log(buf); +// 打印: + +``` + diff --git a/buffer/buf_writeintle_value_offset_bytelength.md b/buffer/buf_writeintle_value_offset_bytelength.md index 70b1ab2a..ed54ae84 100644 --- a/buffer/buf_writeintle_value_offset_bytelength.md +++ b/buffer/buf_writeintle_value_offset_bytelength.md @@ -12,18 +12,13 @@ changes: * `byteLength` {integer} 要写入的字节数。必须满足:`0 < byteLength <= 6`。 * 返回: {integer} `offset` 加上已写入的字节数。 -将 `value` 中的 `byteLength` 个字节写入到 `buf` 中指定的 `offset` 位置。 +将 `value` 中的 `byteLength` 个字节作为小端序写入到 `buf` 中指定的 `offset` 位置。 最高支持 48 位精度。 当 `value` 不是有符号的整数时,行为是未定义的。 ```js const buf = Buffer.allocUnsafe(6); -buf.writeIntBE(0x1234567890ab, 0, 6); - -console.log(buf); -// 打印: - buf.writeIntLE(0x1234567890ab, 0, 6); console.log(buf); diff --git a/buffer/buf_writeuint16be_value_offset.md b/buffer/buf_writeuint16be_value_offset.md index e69de29b..69c127fe 100644 --- a/buffer/buf_writeuint16be_value_offset.md +++ b/buffer/buf_writeuint16be_value_offset.md @@ -0,0 +1,27 @@ + + +* `value` {integer} 要写入 `buf` 的数值。 +* `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 2`。**默认值:** `0`。 +* 返回: {integer} `offset` 加上已写入的字节数。 + +将 `value` 作为大端序写入到 `buf` 中指定的 `offset` 位置。 +`value` 必须是无符号的 16 位整数。 +当 `value` 不是无符号的 16 位整数时,行为是未定义的。 + +```js +const buf = Buffer.allocUnsafe(4); + +buf.writeUInt16BE(0xdead, 0); +buf.writeUInt16BE(0xbeef, 2); + +console.log(buf); +// 打印: +``` + diff --git a/buffer/buf_writeuint16le_value_offset.md b/buffer/buf_writeuint16le_value_offset.md index 4fc41bf0..c2284e00 100644 --- a/buffer/buf_writeuint16le_value_offset.md +++ b/buffer/buf_writeuint16le_value_offset.md @@ -11,19 +11,13 @@ changes: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 2`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的[字节序][endianness](`writeUInt16BE()` 写入为大端序,`writeUInt16LE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +将 `value` 作为小端序写入到 `buf` 中指定的 `offset` 位置。 `value` 必须是无符号的 16 位整数。 当 `value` 不是无符号的 16 位整数时,行为是未定义的。 ```js const buf = Buffer.allocUnsafe(4); -buf.writeUInt16BE(0xdead, 0); -buf.writeUInt16BE(0xbeef, 2); - -console.log(buf); -// 打印: - buf.writeUInt16LE(0xdead, 0); buf.writeUInt16LE(0xbeef, 2); diff --git a/buffer/buf_writeuint32be_value_offset.md b/buffer/buf_writeuint32be_value_offset.md index e69de29b..98bd8155 100644 --- a/buffer/buf_writeuint32be_value_offset.md +++ b/buffer/buf_writeuint32be_value_offset.md @@ -0,0 +1,26 @@ + + +* `value` {integer} 要写入 `buf` 的数值。 +* `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 +* 返回: {integer} `offset` 加上已写入的字节数。 + +将 `value` 作为大端序写入到 `buf` 中指定的 `offset` 位置。 +`value` 必须是无符号的 32 位整数。 +当 `value` 不是无符号的 32 位整数时,行为是未定义的。 + +```js +const buf = Buffer.allocUnsafe(4); + +buf.writeUInt32BE(0xfeedface, 0); + +console.log(buf); +// 打印: +``` + diff --git a/buffer/buf_writeuint32le_value_offset.md b/buffer/buf_writeuint32le_value_offset.md index 4ceb3a40..be7f0f14 100644 --- a/buffer/buf_writeuint32le_value_offset.md +++ b/buffer/buf_writeuint32le_value_offset.md @@ -11,18 +11,13 @@ changes: * `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - 4`。**默认值:** `0`。 * 返回: {integer} `offset` 加上已写入的字节数。 -用指定的[字节序][endianness](`writeUInt32BE()` 写入为大端序,`writeUInt32LE()` 写入为小端序)将 `value` 写入到 `buf` 中指定的 `offset` 位置。 +将 `value` 作为小端序写入到 `buf` 中指定的 `offset` 位置。 `value` 必须是无符号的 32 位整数。 当 `value` 不是无符号的 32 位整数时,行为是未定义的。 ```js const buf = Buffer.allocUnsafe(4); -buf.writeUInt32BE(0xfeedface, 0); - -console.log(buf); -// 打印: - buf.writeUInt32LE(0xfeedface, 0); console.log(buf); diff --git a/buffer/buf_writeuintbe_value_offset_bytelength.md b/buffer/buf_writeuintbe_value_offset_bytelength.md index e69de29b..c2db82bd 100644 --- a/buffer/buf_writeuintbe_value_offset_bytelength.md +++ b/buffer/buf_writeuintbe_value_offset_bytelength.md @@ -0,0 +1,27 @@ + + +* `value` {integer} 要写入 `buf` 的数值。 +* `offset` {integer} 开始写入之前要跳过的字节数。必须满足:`0 <= offset <= buf.length - byteLength`。 +* `byteLength` {integer} 要写入的字节数。必须满足:`0 < byteLength <= 6`。 +* 返回: {integer} `offset` 加上已写入的字节数。 + +将 `value` 中的 `byteLength` 个字节作为大端序写入到 `buf` 中指定的 `offset` 位置。 +最高支持 48 位精度。 +当 `value` 不是无符号的整数时,行为是未定义的。 + +```js +const buf = Buffer.allocUnsafe(6); + +buf.writeUIntBE(0x1234567890ab, 0, 6); + +console.log(buf); +// 打印: +``` + diff --git a/buffer/buf_writeuintle_value_offset_bytelength.md b/buffer/buf_writeuintle_value_offset_bytelength.md index 3aafa26c..8977fbbf 100644 --- a/buffer/buf_writeuintle_value_offset_bytelength.md +++ b/buffer/buf_writeuintle_value_offset_bytelength.md @@ -12,18 +12,13 @@ changes: * `byteLength` {integer} 要写入的字节数。必须满足:`0 < byteLength <= 6`。 * 返回: {integer} `offset` 加上已写入的字节数。 -将 `value` 中的 `byteLength` 个字节写入到 `buf` 中指定的 `offset` 位置。 +将 `value` 中的 `byteLength` 个字节作为小端序写入到 `buf` 中指定的 `offset` 位置。 最高支持 48 位精度。 当 `value` 不是无符号的整数时,行为是未定义的。 ```js const buf = Buffer.allocUnsafe(6); -buf.writeUIntBE(0x1234567890ab, 0, 6); - -console.log(buf); -// 打印: - buf.writeUIntLE(0x1234567890ab, 0, 6); console.log(buf); diff --git a/buffer/buffer.md b/buffer/buffer.md index 95914372..66517be1 100644 --- a/buffer/buffer.md +++ b/buffer/buffer.md @@ -3,15 +3,13 @@ > 稳定性: 2 - 稳定 -在 Node.js 中,`Buffer` 对象用于以字节序列的形式来表示二进制数据。 -许多 Node.js 的 API(例如流和文件系统操作)都支持 `Buffer`,因为与操作系统或其他进程的交互通常总是以二进制数据的形式发生。 + -`Buffer` 类是 JavaScript 语言内置的 [`Uint8Array`] 类的子类。 -支持许多涵盖其他用例的额外方法。 -只要支持 `Buffer` 的地方,Node.js API 都可以接受普通的 [`Uint8Array`]。 +`Buffer` 对象用于表示固定长度的字节序列。 +许多 Node.js API 都支持 `Buffer`。 -`Buffer` 的实例(通常是 [`Uint8Array`] 的实例),类似于从 `0` 到 `255` 之间的整数数组,但对应于固定大小的内存块,并且不能包含任何其他值。 -一个 `Buffer` 的大小在创建时确定,且无法更改。 +`Buffer` 类是 JavaScript 的 [`Uint8Array`] 类的子类,且继承时带上了涵盖额外用例的方法。 +只要支持 `Buffer` 的地方,Node.js API 都可以接受普通的 [`Uint8Array`]。 `Buffer` 类在全局作用域中,因此无需使用 `require('buffer').Buffer`。 diff --git a/buffer/buffer_constants.md b/buffer/buffer_constants.md index 3510528c..7afae888 100644 --- a/buffer/buffer_constants.md +++ b/buffer/buffer_constants.md @@ -2,5 +2,3 @@ added: v8.2.0 --> -`buffer.constants` 是在 `require('buffer')` 返回的 `buffer` 模块上,而不是在 `Buffer` 全局变量或 `Buffer` 实例上。 - diff --git a/buffer/buffer_inspect_max_bytes.md b/buffer/buffer_inspect_max_bytes.md index 72cb520e..75fd7731 100644 --- a/buffer/buffer_inspect_max_bytes.md +++ b/buffer/buffer_inspect_max_bytes.md @@ -8,5 +8,3 @@ added: v0.5.4 这可以被用户模块重写。 有关 `buf.inspect()` 行为的更多详细信息,参见 [`util.inspect()`]。 -该属性是在 `require('buffer')` 返回的 `buffer` 模块上,而不是在 `Buffer` 全局变量或 `Buffer` 实例上。 - diff --git a/buffer/buffer_kmaxlength.md b/buffer/buffer_kmaxlength.md index b805d714..c56b1430 100644 --- a/buffer/buffer_kmaxlength.md +++ b/buffer/buffer_kmaxlength.md @@ -6,5 +6,3 @@ added: v3.0.0 [`buffer.constants.MAX_LENGTH`] 的别名。 -该属性是在 `require('buffer')` 返回的 `buffer` 模块上,而不是在 `Buffer` 全局变量或 `Buffer` 实例上。 - diff --git a/buffer/buffer_module_apis.md b/buffer/buffer_module_apis.md new file mode 100644 index 00000000..d60bbc41 --- /dev/null +++ b/buffer/buffer_module_apis.md @@ -0,0 +1,5 @@ + +While, the `Buffer` object is available as a global, there are additional +`Buffer`-related APIs that are available only via the `buffer` module +accessed using `require('buffer')`. + diff --git a/buffer/buffer_transcode_source_fromenc_toenc.md b/buffer/buffer_transcode_source_fromenc_toenc.md index 74a31559..01a2ad61 100644 --- a/buffer/buffer_transcode_source_fromenc_toenc.md +++ b/buffer/buffer_transcode_source_fromenc_toenc.md @@ -31,5 +31,3 @@ console.log(newBuf.toString('ascii')); 因为欧元符号(`€`)无法在 US-ASCII 中表示,所以在转码 `Buffer` 时使用 `?` 代替。 -该属性是在 `require('buffer')` 返回的 `buffer` 模块上,而不是在 `Buffer` 全局变量或 `Buffer` 实例上。 - diff --git a/buffer/buffers_and_character_encodings.md b/buffer/buffers_and_character_encodings.md index 38e56360..2aecaff3 100644 --- a/buffer/buffers_and_character_encodings.md +++ b/buffer/buffers_and_character_encodings.md @@ -48,6 +48,7 @@ Node.js 还支持以下两种二进制转文本的编码。 * `'base64'`: [Base64] 编码。 当从字符串创建 `Buffer` 时,此编码也会正确地接受 [RFC 4648 第 5 节][RFC 4648, Section 5]中指定的 “URL 和文件名安全字母”。 + base64 编码的字符串中包含的空格字符(例如空格、制表符和换行)会被忽略。 * `'hex'`: 将每个字节编码成两个十六进制的字符。 当解码仅包含有效的十六进制字符的字符串时,可能会发生数据截断。 diff --git a/buffer/buffers_and_typedarrays.md b/buffer/buffers_and_typedarrays.md index d73f3ce1..179a9518 100644 --- a/buffer/buffers_and_typedarrays.md +++ b/buffer/buffers_and_typedarrays.md @@ -5,9 +5,8 @@ changes: description: The `Buffer`s class now inherits from `Uint8Array`. --> -`Buffer` 实例也是 [`Uint8Array`] 实例,这是该语言用于处理二进制数据的内置类。 -[`Uint8Array`] 依次是 [`TypedArray`] 的子类。 -因此,所有 [`TypedArray`] 的方法在 `Buffer` 上也可用。 +`Buffer` 实例也是 JavaScript 的 [`Uint8Array`] 和 [`TypedArray`] 实例。 +所有的 [`TypedArray`] 方法在 `Buffer` 上也可用。 但是,`Buffer` 的 API 和 [`TypedArray`] 的 API 之间存在细微的不兼容。 主要表现在: @@ -18,18 +17,31 @@ changes: * [`buf.toString()`] 与它在 `TypedArray` 上的等价物并不兼容。 * 一些方法,例如 [`buf.indexOf()`],支持额外的参数。 -有两种方法可以从一个 `Buffer` 创建新的 [`TypedArray`] 实例。 +有两种方法可以从一个 `Buffer` 创建新的 [`TypedArray`] 实例: -当将一个 `Buffer` 传给 [`TypedArray`] 的构造函数时,该 `Buffer` 的元素会被拷贝且,且会被解析为一个整数数组,而不是目标类型的字节数组。 -例如,`new Uint32Array(Buffer.from([1, 2, 3, 4]))` 会创建一个带有 4 个元素 `[1, 2, 3, 4]` 的 [`Uint32Array`],而不是带有单个元素 `[0x1020304]` 或 `[0x4030201]` 的 [`Uint32Array`]。 +* 将 `Buffer` 传给 [`TypedArray`] 的构造函数,则会拷贝 `Buffer` 的内容(会被解析为整数数组,而不是目标类型的字节序列)。 +```js +const buf = Buffer.from([1, 2, 3, 4]); +const uint32array = new Uint32Array(buf); + +console.log(uint32array); + +// 打印: Uint32Array(4) [ 1, 2, 3, 4 ] +``` -为了创建与 `Buffer` 共享其内存的 [`TypedArray`],可以将底层的 [`ArrayBuffer`] 传给 [`TypedArray`] 的构造函数: +* 传入 `Buffer` 底层的 [`ArrayBuffer`],则会创建与 `Buffer` 共享其内存的 [`TypedArray`]: ```js const buf = Buffer.from('hello', 'utf16le'); const uint16arr = new Uint16Array( - buf.buffer, buf.byteOffset, buf.length / Uint16Array.BYTES_PER_ELEMENT); + buf.buffer, + buf.byteOffset, + buf.length / Uint16Array.BYTES_PER_ELEMENT); + +console.log(uint16array); + +// 打印: Uint16Array(5) [ 104, 101, 108, 108, 111 ] ``` 也可以通过使用 `TypedArray` 对象的 `.buffer` 属性,以相同的方式来创建一个与 [`TypedArray`] 实例共享相同分配内存的新 `Buffer`。 @@ -43,6 +55,7 @@ arr[1] = 4000; // 拷贝 `arr` 的内容。 const buf1 = Buffer.from(arr); + // 与 `arr` 共享内存。 const buf2 = Buffer.from(arr.buffer); diff --git a/child_process/child_process.md b/child_process/child_process.md index c65805c2..137d5f0b 100644 --- a/child_process/child_process.md +++ b/child_process/child_process.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `child_process` 模块提供了衍生子进程(以一种与 popen(3) 类似但不相同的方式)的能力。 此功能主要由 [`child_process.spawn()`] 函数提供: diff --git a/child_process/child_process_exec_command_options_callback.md b/child_process/child_process_exec_command_options_callback.md index 09f092b8..bc7de2ee 100644 --- a/child_process/child_process_exec_command_options_callback.md +++ b/child_process/child_process_exec_command_options_callback.md @@ -14,7 +14,7 @@ changes: **默认值:** `process.env`。 * `encoding` {string} **默认值:** `'utf8'`。 * `shell` {string} 用于执行命令。 - 参见 [shell 的要求][Shell Requirements]和[默认的 Windows shell][Default Windows Shell]。 + 参见 [shell 的要求][Shell requirements]和[默认的 Windows shell][Default Windows shell]。 **默认值:** Unix 上是 `'/bin/sh'`,Windows 上是 `process.env.ComSpec`。 * `timeout` {number} **默认值:** `0`。 * `maxBuffer` {number} stdout 或 stderr 上允许的最大数据量(以字节为单位)。 @@ -49,8 +49,9 @@ exec('echo "\\$HOME 变量为 $HOME"'); 如果提供了 `callback` 函数,则调用时会传入参数 `(error, stdout, stderr)`。 当成功时,则 `error` 会为 `null`。 当报错时,则 `error` 会是 [`Error`] 的实例。 -`error.code` 属性是子进程的退出码,`error.signal` 会被设为终止进程的信号。 -除 `0` 以外的任何退出码都会被视为错误。 +`error.code` 属性是进程的退出码。 +按照惯例,除 `0` 以外的任何退出码均表示错误。 +`error.signal` 是终止进程的信号。 传给回调的 `stdout` 和 `stderr` 参数会包含子进程的 stdout 和 stderr 输出。 默认情况下,Node.js 会将输出解码为 UTF-8 并将字符串传给回调。 diff --git a/child_process/child_process_execfile_file_args_options_callback.md b/child_process/child_process_execfile_file_args_options_callback.md index fb069e94..76e1f42b 100644 --- a/child_process/child_process_execfile_file_args_options_callback.md +++ b/child_process/child_process_execfile_file_args_options_callback.md @@ -29,7 +29,7 @@ changes: * `shell` {boolean|string} 如果为 `true`,则在 shell 中运行 `command`。 在 Unix 上使用 `'/bin/sh'`,在 Windows 上使用 `process.env.ComSpec`。 可以将不同的 shell 指定为字符串。 - 参见 [shell 的要求][Shell Requirements]和[默认的 Windows shell][Default Windows Shell]。 + 参见 [shell 的要求][Shell requirements]和[默认的 Windows shell][Default Windows shell]。 **默认值:** `false`(没有 shell)。 * `callback` {Function} 当进程终止时调用并传入输出。 * `error` {Error} diff --git a/child_process/child_process_execfilesync_file_args_options.md b/child_process/child_process_execfilesync_file_args_options.md index 78eef28f..1b648b7c 100644 --- a/child_process/child_process_execfilesync_file_args_options.md +++ b/child_process/child_process_execfilesync_file_args_options.md @@ -35,7 +35,7 @@ changes: * `shell` {boolean|string} 如果为 `true`,则在 shell 中运行 `command`。 在 Unix 上使用 `'/bin/sh'`,在 Windows 上使用 `process.env.ComSpec`。 可以将不同的 shell 指定为字符串。 - 参见 [shell 的要求][Shell Requirements]和[默认的 Windows shell][Default Windows Shell]。 + 参见 [shell 的要求][Shell requirements]和[默认的 Windows shell][Default Windows shell]。 **默认值:** `false`(没有 shell)。 * 返回: {Buffer|string} 命令的 stdout。 diff --git a/child_process/child_process_execsync_command_options.md b/child_process/child_process_execsync_command_options.md index 3cabd514..63410988 100644 --- a/child_process/child_process_execsync_command_options.md +++ b/child_process/child_process_execsync_command_options.md @@ -23,7 +23,7 @@ changes: * `env` {Object} 环境变量的键值对。 **默认值:** `process.env`。 * `shell` {string} 用于执行命令。 - 参见 [shell 的要求][Shell Requirements]和[默认的 Windows shell][Default Windows Shell]。 + 参见 [shell 的要求][Shell requirements]和[默认的 Windows shell][Default Windows shell]。 **默认值:** Unix 上是 `'/bin/sh'`,Windows 上是 `process.env.ComSpec`。 * `uid` {number} 设置进程的用户标识,参见 setuid(2)。 * `gid` {number} 设置进程的群组标识,参见 setgid(2)。 diff --git a/child_process/child_process_fork_modulepath_args_options.md b/child_process/child_process_fork_modulepath_args_options.md index f7f002ad..e2390273 100644 --- a/child_process/child_process_fork_modulepath_args_options.md +++ b/child_process/child_process_fork_modulepath_args_options.md @@ -27,7 +27,7 @@ changes: **默认值:** `process.execArgv`。 * `serialization` {string} 指定用于在进程之间发送消息的序列化类型。 可能的值为 `'json'` 和 `'advanced'`。 - 详见[高级序列化][Advanced Serialization]。 + 详见[高级序列化][Advanced serialization]。 **默认值:** `'json'`。 * `silent` {boolean} 如果为 `true`,则子进程的 stdin、stdout 和 stderr 会被 pipe 到父进程,否则它们会继承自父进程,详见 [`child_process.spawn()`] 的 [`stdio`] 中的 `'pipe'` 和 `'inherit'` 选项。 **默认值:** `false`。 diff --git a/child_process/child_process_spawn_command_args_options.md b/child_process/child_process_spawn_command_args_options.md index 889ddd10..32faf135 100644 --- a/child_process/child_process_spawn_command_args_options.md +++ b/child_process/child_process_spawn_command_args_options.md @@ -32,12 +32,12 @@ changes: * `gid` {number} 设置进程的群组标识,参见 setgid(2)。 * `serialization` {string} 指定用于在进程之间发送消息的序列化类型。 可能的值为 `'json'` 和 `'advanced'`。 - 详见[高级序列化][Advanced Serialization]。 + 详见[高级序列化][Advanced serialization]。 **默认值:** `'json'`。 * `shell` {boolean|string} 如果为 `true`,则在 shell 中运行 `command`。 在 Unix 上使用 `'/bin/sh'`,在 Windows 上使用 `process.env.ComSpec`。 可以将不同的 shell 指定为字符串。 - 参见 [shell 的要求][Shell Requirements]和[默认的 Windows shell][Default Windows Shell]。 + 参见 [shell 的要求][Shell requirements]和[默认的 Windows shell][Default Windows shell]。 **默认值:** `false`(没有 shell)。 * `windowsVerbatimArguments` {boolean} 在 Windows 上不为参数加上引号或转义。 在 Unix 上会被忽略。 diff --git a/child_process/child_process_spawnsync_command_args_options.md b/child_process/child_process_spawnsync_command_args_options.md index 7ed36a06..8ef82bed 100644 --- a/child_process/child_process_spawnsync_command_args_options.md +++ b/child_process/child_process_spawnsync_command_args_options.md @@ -38,7 +38,7 @@ changes: * `shell` {boolean|string} 如果为 `true`,则在 shell 中运行 `command`。 在 Unix 上使用 `'/bin/sh'`,在 Windows 上使用 `process.env.ComSpec`。 可以将不同的 shell 指定为字符串。 - 参见 [shell 的要求][Shell Requirements]和[默认的 Windows shell][Default Windows Shell]。 + 参见 [shell 的要求][Shell requirements]和[默认的 Windows shell][Default Windows shell]。 **默认值:** `false`(没有 shell)。 * `windowsVerbatimArguments` {boolean} 在 Windows 上不为参数加上引号或转义。在 Unix 上会被忽略。如果指定了 `shell` 并且是 CMD,则自动设为 `true`。**默认值:** `false`。 * `windowsHide` {boolean} 隐藏子进程的控制台窗口(在 Windows 系统上通常会创建)。**默认值:** `false`。 diff --git a/child_process/event_message.md b/child_process/event_message.md index 11ebe09a..740e10ca 100644 --- a/child_process/event_message.md +++ b/child_process/event_message.md @@ -11,6 +11,6 @@ added: v0.5.9 收到的消息可能跟最初发送的不完全一样。 如果在衍生子进程时使用了 `serialization` 选项设置为 `'advanced'`,则 `message` 参数可以包含 JSON 无法表示的数据。 -详见[高级序列化][Advanced Serialization]。 +详见[高级序列化][Advanced serialization]。 diff --git a/child_process/example_sending_a_socket_object.md b/child_process/example_sending_a_socket_object.md index 0001ea5e..f45146b9 100644 --- a/child_process/example_sending_a_socket_object.md +++ b/child_process/example_sending_a_socket_object.md @@ -37,9 +37,8 @@ process.on('message', (m, socket) => { }); ``` -一旦一个 socket 已被传给了子进程,则父进程不再能够跟踪 socket 何时被销毁。 -为了表明这个,`.connections` 属性会变成 `null`。 -当发生这种情况时,建议不要使用 `.maxConnections`。 +不要使用已被传给子进程的 socket 上的 `.maxConnections`。 +父进程无法追踪 socket 何时被销毁。 -建议在子进程中的任何 `'message'` 句柄都需要验证 `socket` 是否存在,因为连接可能会在它发送给子进程的这段时间内被关闭。 +子进程中的任何 `'message'` 句柄都应该验证 `socket` 是否存在,因为连接可能会在它发送给子进程的这段时间内被关闭。 diff --git a/cli/enable_source_maps.md b/cli/enable_source_maps.md index 31b37e66..8db73287 100644 --- a/cli/enable_source_maps.md +++ b/cli/enable_source_maps.md @@ -4,7 +4,7 @@ added: v12.12.0 > Stability: 1 - Experimental -Enable experimental Source Map V3 support for stack traces. +Enable experimental Source Map v3 support for stack traces. Currently, overriding `Error.prepareStackTrace` is ignored when the `--enable-source-maps` flag is set. diff --git a/cli/max_old_space_size_size_in_mbytes.md b/cli/max_old_space_size_size_in_megabytes.md similarity index 100% rename from cli/max_old_space_size_size_in_mbytes.md rename to cli/max_old_space_size_size_in_megabytes.md diff --git a/cli/report_dir_directory_report_directory_directory.md b/cli/report_dir_directory_report_directory_directory.md index 638b26a3..3629cef8 100644 --- a/cli/report_dir_directory_report_directory_directory.md +++ b/cli/report_dir_directory_report_directory_directory.md @@ -3,7 +3,7 @@ added: v11.8.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This option is no longer considered experimental. + description: This option is no longer experimental. - version: v12.0.0 pr-url: https://github.com/nodejs/node/pull/27312 description: Changed from `--diagnostic-report-directory` to diff --git a/cli/report_filename_filename.md b/cli/report_filename_filename.md index c5d136e7..225c906a 100644 --- a/cli/report_filename_filename.md +++ b/cli/report_filename_filename.md @@ -3,7 +3,7 @@ added: v11.8.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This option is no longer considered experimental. + description: This option is no longer experimental. - version: v12.0.0 pr-url: https://github.com/nodejs/node/pull/27312 description: changed from `--diagnostic-report-filename` to diff --git a/cli/report_on_fatalerror.md b/cli/report_on_fatalerror.md index a6fa6bd5..8d3dd003 100644 --- a/cli/report_on_fatalerror.md +++ b/cli/report_on_fatalerror.md @@ -3,7 +3,7 @@ added: v11.8.0 changes: - version: v14.0.0 pr-url: https://github.com/nodejs/node/pull/32496 - description: This option is no longer considered experimental. + description: This option is no longer experimental. - version: v12.0.0 pr-url: https://github.com/nodejs/node/pull/27312 description: changed from `--diagnostic-report-on-fatalerror` to diff --git a/cli/report_on_signal.md b/cli/report_on_signal.md index 04e57156..856219c1 100644 --- a/cli/report_on_signal.md +++ b/cli/report_on_signal.md @@ -3,7 +3,7 @@ added: v11.8.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This option is no longer considered experimental. + description: This option is no longer experimental. - version: v12.0.0 pr-url: https://github.com/nodejs/node/pull/27312 description: changed from `--diagnostic-report-on-signal` to diff --git a/cli/report_signal_signal.md b/cli/report_signal_signal.md index cb8136c8..90004202 100644 --- a/cli/report_signal_signal.md +++ b/cli/report_signal_signal.md @@ -3,7 +3,7 @@ added: v11.8.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This option is no longer considered experimental. + description: This option is no longer experimental. - version: v12.0.0 pr-url: https://github.com/nodejs/node/pull/27312 description: changed from `--diagnostic-report-signal` to diff --git a/cli/report_uncaught_exception.md b/cli/report_uncaught_exception.md index 2ba68850..b25da0c1 100644 --- a/cli/report_uncaught_exception.md +++ b/cli/report_uncaught_exception.md @@ -3,7 +3,7 @@ added: v11.8.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This option is no longer considered experimental. + description: This option is no longer experimental. - version: v12.0.0 pr-url: https://github.com/nodejs/node/pull/27312 description: changed from `--diagnostic-report-uncaught-exception` to diff --git a/cli/source_map_cache.md b/cli/source_map_cache.md index b76a8a68..a18038b0 100644 --- a/cli/source_map_cache.md +++ b/cli/source_map_cache.md @@ -1,12 +1,12 @@ > Stability: 1 - Experimental -If found, Source Map data is appended to the top-level key `source-map-cache` +If found, source map data is appended to the top-level key `source-map-cache` on the JSON coverage object. `source-map-cache` is an object with keys representing the files source maps were extracted from, and values which include the raw source-map URL -(in the key `url`), the parsed Source Map V3 information (in the key `data`), +(in the key `url`), the parsed Source Map v3 information (in the key `data`), and the line lengths of the source file (in the key `lineLengths`). ```json diff --git a/cluster/cluster.md b/cluster/cluster.md index 673437c8..b8db65ce 100644 --- a/cluster/cluster.md +++ b/cluster/cluster.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + 单个 Node.js 实例运行在单个线程中。 为了充分利用多核系统,有时需要启用一组 Node.js 进程去处理负载任务。 diff --git a/cluster/cluster_settings.md b/cluster/cluster_settings.md index 184943b8..c5bb1e39 100644 --- a/cluster/cluster_settings.md +++ b/cluster/cluster_settings.md @@ -25,7 +25,7 @@ changes: * `exec` {string} 工作进程的文件路径。**默认值:** `process.argv[1]`。 * `args` {string[]} 传给工作进程的字符串参数。**默认值:** `process.argv.slice(2)`。 * `cwd` {string} 工作进程的当前工作目录。**默认值:** `undefined`(从父进程继承)。 - * `serialization` {string} 指定用于在进程之间发送消息的序列化类型。可能的值为 `'json'` 和 `'advanced'`。有关更多详细信息,请参见[`child_process` 的高级序列化][Advanced Serialization for `child_process`]。**默认值:** `false`。 + * `serialization` {string} 指定用于在进程之间发送消息的序列化类型。可能的值为 `'json'` 和 `'advanced'`。有关更多详细信息,请参见[`child_process` 的高级序列化][Advanced serialization for `child_process`]。**默认值:** `false`。 * `silent` {boolean} 是否需要发送输出到父进程的 stdio。**默认值:** `false`。 * `stdio` {Array} 配置衍生的进程的 stdio。 由于 cluster 模块运行依赖于 IPC,这个配置必须包含 `'ipc'`。如果提供了这个选项,则覆盖 `silent`。 * `uid` {number} 设置进程的用户标识符。参见 setuid(2)。 diff --git a/console/console.md b/console/console.md index 90856d5e..f0204085 100644 --- a/console/console.md +++ b/console/console.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `console` 模块提供了一个简单的调试控制台,类似于 Web 浏览器提供的 JavaScript 控制台。 该模块导出两个特定组件: diff --git a/crypto/crypto.md b/crypto/crypto.md index 750ce89a..1f0b426d 100644 --- a/crypto/crypto.md +++ b/crypto/crypto.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `crypto` 模块提供了加密功能,包括对 OpenSSL 的哈希、HMAC、加密、解密、签名、以及验证功能的一整套封装。 使用 `require('crypto')` 来访问该模块。 diff --git a/crypto/crypto_constants.md b/crypto/crypto_constants.md index 2fff481b..877a4629 100644 --- a/crypto/crypto_constants.md +++ b/crypto/crypto_constants.md @@ -4,5 +4,5 @@ added: v6.3.0 * Returns: {Object} An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are - described in [Crypto Constants][]. + described in [Crypto constants][]. diff --git a/crypto/node_js_crypto_constants.md b/crypto/node_js_crypto_constants.md index c62f701f..0d3e06e5 100644 --- a/crypto/node_js_crypto_constants.md +++ b/crypto/node_js_crypto_constants.md @@ -85,5 +85,6 @@ + diff --git a/crypto/other_openssl_constants.md b/crypto/other_openssl_constants.md index 1f3ca60f..92aba22f 100644 --- a/crypto/other_openssl_constants.md +++ b/crypto/other_openssl_constants.md @@ -1,4 +1,6 @@ +See the [list of SSL OP Flags][] for details. + diff --git a/debugger/v8_inspector_integration_for_node_js.md b/debugger/v8_inspector_integration_for_node_js.md index c4150278..371303b5 100644 --- a/debugger/v8_inspector_integration_for_node_js.md +++ b/debugger/v8_inspector_integration_for_node_js.md @@ -17,6 +17,6 @@ For help, see: https://nodejs.org/en/docs/inspector 如果 Chrome 浏览器的版本低于 66.0.3345.0,则在上述的 URL 中使用 `inspector.html` 而不是 `js_app.html`。 -Chrome 开发者工具目前还不支持调试[工作线程][Worker Threads]。 +Chrome 开发者工具目前还不支持调试[工作线程][worker threads]。 可以使用 [ndb] 来调试它们。 diff --git a/deprecations/dep0085_asynchooks_sensitive_api.md b/deprecations/dep0085_asynchooks_sensitive_api.md index dd061e03..573d7154 100644 --- a/deprecations/dep0085_asynchooks_sensitive_api.md +++ b/deprecations/dep0085_asynchooks_sensitive_api.md @@ -12,7 +12,7 @@ changes: Type: End-of-Life -The AsyncHooks Sensitive API was never documented and had various minor issues. +The AsyncHooks sensitive API was never documented and had various minor issues. Use the `AsyncResource` API instead. See . diff --git a/deprecations/dep0143_transform_transformstate.md b/deprecations/dep0143_transform_transformstate.md index bd0996af..435fd26d 100644 --- a/deprecations/dep0143_transform_transformstate.md +++ b/deprecations/dep0143_transform_transformstate.md @@ -8,123 +8,4 @@ Type: Runtime `Transform._transformState` will be removed in future versions where it is no longer required due to simplification of the implementation. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + diff --git a/deprecations/dep0144_module_parent.md b/deprecations/dep0144_module_parent.md new file mode 100644 index 00000000..35e10214 --- /dev/null +++ b/deprecations/dep0144_module_parent.md @@ -0,0 +1,32 @@ + + +Type: Documentation-only + +A CommonJS module can access the first module that required it using +`module.parent`. This feature is deprecated because it does not work +consistently in the presence of ECMAScript modules and because it gives an +inaccurate representation of the CommonJS module graph. + +Some modules use it to check if they are the entry point of the current process. +Instead, it is recommended to compare `require.main` and `module`: + +```js +if (require.main === module) { + // Code section that will run only if current file is the entry point. +} +``` + +When looking for the CommonJS modules that have required the current one, +`require.cache` and `module.children` can be used: + +```js +const moduleParents = Object.values(require.cache) + .filter((m) => m.children.includes(module)); +``` + + diff --git a/deprecations/dep0145_socket_buffersize.md b/deprecations/dep0145_socket_buffersize.md new file mode 100644 index 00000000..fba179b4 --- /dev/null +++ b/deprecations/dep0145_socket_buffersize.md @@ -0,0 +1,133 @@ + + +Type: Documentation-only + +[`socket.bufferSize`][] is just an alias for [`writable.writableLength`][]. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dgram/examples_ipv6_outgoing_multicast_interface.md b/dgram/example_ipv6_outgoing_multicast_interface.md similarity index 100% rename from dgram/examples_ipv6_outgoing_multicast_interface.md rename to dgram/example_ipv6_outgoing_multicast_interface.md diff --git a/dgram/socket_addmembership_multicastaddress_multicastinterface.md b/dgram/socket_addmembership_multicastaddress_multicastinterface.md index a82072d2..b032bab1 100644 --- a/dgram/socket_addmembership_multicastaddress_multicastinterface.md +++ b/dgram/socket_addmembership_multicastaddress_multicastinterface.md @@ -9,6 +9,9 @@ added: v0.6.9 若 `multicastInterface` 参数未指定,则操作系统将会选择一个接口并向其添加成员。 要为所有可用的接口添加成员,可以在每个接口上调用一次 `addMembership` 方法。 +When called on an unbound socket, this method will implicitly bind to a random +port, listening on all interfaces. + 当多个 `cluster` 工作进程之间共享 UDP socket 时,则 `socket.addMembership()` 函数必须只能被调用一次,否则将会发生 `EADDRINUSE` 错误: ```js diff --git a/dgram/socket_address.md b/dgram/socket_address.md index 58565220..f73739a4 100644 --- a/dgram/socket_address.md +++ b/dgram/socket_address.md @@ -7,3 +7,5 @@ added: v0.1.99 返回一个包含 socket 地址信息的对象。 对于 UDP socket,该对象将包含 `address`、`family` 和 `port` 属性。 +This method throws `EBADF` if called on an unbound socket. + diff --git a/dgram/socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface.md b/dgram/socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface.md index 3577e778..6a2806e1 100644 --- a/dgram/socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface.md +++ b/dgram/socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface.md @@ -14,3 +14,6 @@ is not specified, the operating system will choose one interface and will add membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface. +When called on an unbound socket, this method will implicitly bind to a random +port, listening on all interfaces. + diff --git a/dgram/socket_disconnect.md b/dgram/socket_disconnect.md index acb40ce6..94eb40e6 100644 --- a/dgram/socket_disconnect.md +++ b/dgram/socket_disconnect.md @@ -3,4 +3,4 @@ added: v12.0.0 --> 一个将相连的 `dgram.Socket` 与远程地址断掉的同步函数。 -在一个已经未连接的 socket 上尝试调用 `disconnect()` 会导致一个 [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][] 异常。 +在一个未绑定或已经断开连接的 socket 上尝试调用 `disconnect()` 会导致一个 [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][] 异常。 diff --git a/dgram/socket_getrecvbuffersize.md b/dgram/socket_getrecvbuffersize.md index 41e7dee2..c49bc1ff 100644 --- a/dgram/socket_getrecvbuffersize.md +++ b/dgram/socket_getrecvbuffersize.md @@ -4,3 +4,4 @@ added: v8.7.0 * 返回 {number} `SO_RCVBUF` socket 接收到的 buffer 的大小,以字节为单位。 +This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. diff --git a/dgram/socket_getsendbuffersize.md b/dgram/socket_getsendbuffersize.md index 55afbaee..4d796c4e 100644 --- a/dgram/socket_getsendbuffersize.md +++ b/dgram/socket_getsendbuffersize.md @@ -4,3 +4,4 @@ added: v8.7.0 * 返回 {number} `SO_SNDBUF` socket 发送的 buffer 的大小,以字节为单位。 +This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. diff --git a/dgram/socket_remoteaddress.md b/dgram/socket_remoteaddress.md index cf256852..d7cbb050 100644 --- a/dgram/socket_remoteaddress.md +++ b/dgram/socket_remoteaddress.md @@ -5,6 +5,6 @@ added: v12.0.0 * Returns: {Object} Returns an object containing the `address`, `family`, and `port` of the remote -endpoint. It throws an [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][] exception if the -socket is not connected. +endpoint. This method throws an [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][] exception +if the socket is not connected. diff --git a/dgram/socket_send_msg_offset_length_port_address_callback.md b/dgram/socket_send_msg_offset_length_port_address_callback.md index 0a3d59e7..87ae7876 100644 --- a/dgram/socket_send_msg_offset_length_port_address_callback.md +++ b/dgram/socket_send_msg_offset_length_port_address_callback.md @@ -57,6 +57,8 @@ changes: 偏移量和长度是可选的,但如其中一个被指定则另一个也必须被指定。 另外,它们只在第一个参数是 `Buffer`、`TypedArray` 或 `DataView` 的情况下才能被使用。 +This method throws [`ERR_SOCKET_BAD_PORT`][] if called on an unbound socket. + 示例,发送 UDP 包到 `localhost` 上的某个端口: ```js diff --git a/dgram/socket_setbroadcast_flag.md b/dgram/socket_setbroadcast_flag.md index 0d43b2c2..51963971 100644 --- a/dgram/socket_setbroadcast_flag.md +++ b/dgram/socket_setbroadcast_flag.md @@ -6,3 +6,5 @@ added: v0.6.9 设置或清除 `SO_BROADCAST` socket 选项。 当设置为 `true`, UDP 包可能会被发送到一个本地接口的广播地址。 + +This method throws `EBADF` if called on an unbound socket. diff --git a/dgram/socket_setmulticastinterface_multicastinterface.md b/dgram/socket_setmulticastinterface_multicastinterface.md index 9f04ac69..cf55a0c7 100644 --- a/dgram/socket_setmulticastinterface_multicastinterface.md +++ b/dgram/socket_setmulticastinterface_multicastinterface.md @@ -23,3 +23,5 @@ also use explicit scope in addresses, so only packets sent to a multicast address without specifying an explicit scope are affected by the most recent successful use of this call. +This method throws `EBADF` if called on an unbound socket. + diff --git a/dgram/socket_setmulticastloopback_flag.md b/dgram/socket_setmulticastloopback_flag.md index 543c2bff..f018c882 100644 --- a/dgram/socket_setmulticastloopback_flag.md +++ b/dgram/socket_setmulticastloopback_flag.md @@ -6,4 +6,4 @@ added: v0.3.8 设置或清除 `IP_MULTICAST_LOOP` socket 选项。当设置为 `true`, 多播数据包也将在本地接口接收。 - +This method throws `EBADF` if called on an unbound socket. diff --git a/dgram/socket_setmulticastttl_ttl.md b/dgram/socket_setmulticastttl_ttl.md index ccc23f57..f72e51aa 100644 --- a/dgram/socket_setmulticastttl_ttl.md +++ b/dgram/socket_setmulticastttl_ttl.md @@ -12,3 +12,4 @@ added: v0.3.8 `ttl` 参数可以是 `0` 到 `255` 之间。 在大多数系统上,默认值是 `1`。 +This method throws `EBADF` if called on an unbound socket. diff --git a/dgram/socket_setrecvbuffersize_size.md b/dgram/socket_setrecvbuffersize_size.md index 153d2966..6e18da1b 100644 --- a/dgram/socket_setrecvbuffersize_size.md +++ b/dgram/socket_setrecvbuffersize_size.md @@ -7,3 +7,5 @@ added: v8.7.0 设置 `SO_RCVBUF` socket 选项。 设置 socket 接收 buffer 的最大值,以字节为单位。 + +This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. diff --git a/dgram/socket_setsendbuffersize_size.md b/dgram/socket_setsendbuffersize_size.md index d21b28b0..e1b267bd 100644 --- a/dgram/socket_setsendbuffersize_size.md +++ b/dgram/socket_setsendbuffersize_size.md @@ -6,3 +6,5 @@ added: v8.7.0 设置 `SO_SNDBUF` socket 选项。 设置 socket 发送 buffer 的最大值,以字节为单位。 + +This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. diff --git a/dgram/socket_setttl_ttl.md b/dgram/socket_setttl_ttl.md index 380a9577..eaf7b71b 100644 --- a/dgram/socket_setttl_ttl.md +++ b/dgram/socket_setttl_ttl.md @@ -13,3 +13,4 @@ added: v0.1.101 `ttl` 参数可以是 `0` 到 `255` 之间。 在大多数系统上,默认值是 `64`。 +This method throws `EBADF` if called on an unbound socket. diff --git a/dgram/udp_datagram_sockets.md b/dgram/udp_datagram_sockets.md index 38915f6c..a0cc28f8 100644 --- a/dgram/udp_datagram_sockets.md +++ b/dgram/udp_datagram_sockets.md @@ -5,6 +5,8 @@ + + `dgram` 模块提供了 UDP 数据包 socket 的实现。 ```js diff --git a/dns/dns.md b/dns/dns.md index ba5b730b..53ff8f29 100644 --- a/dns/dns.md +++ b/dns/dns.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `dns` 模块用于启用名称解析。 例如,使用它来查找主机名的 IP 地址。 diff --git a/dns/dnspromises_setservers_servers.md b/dns/dnspromises_setservers_servers.md index cb10ae37..74a6d29a 100644 --- a/dns/dnspromises_setservers_servers.md +++ b/dns/dnspromises_setservers_servers.md @@ -23,7 +23,7 @@ The `dnsPromises.setServers()` method must not be called while a DNS query is in progress. This method works much like -[resolve.conf](http://man7.org/linux/man-pages/man5/resolv.conf.5.html). +[resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will *not* attempt to resolve with subsequent servers provided. Fallback DNS servers will only be used if the diff --git a/dns/supported_getaddrinfo_flags.md b/dns/supported_getaddrinfo_flags.md index 02e14106..230a8678 100644 --- a/dns/supported_getaddrinfo_flags.md +++ b/dns/supported_getaddrinfo_flags.md @@ -7,7 +7,7 @@ changes: 以下内容可以作为 hints 标志传给 [`dns.lookup()`]。 -* `dns.ADDRCONFIG`: 返回当前系统支持的地址类型。例如,如果当前系统至少配置了一个 IPv4 地址,则返回 IPv4 地址。不考虑回环地址。 +* `dns.ADDRCONFIG`: Limits returned address types to the types of non-loopback addresses configured on the system. 例如,如果当前系统至少配置了一个 IPv4 地址,则返回 IPv4 地址。 * `dns.V4MAPPED`: 如果指定了 IPv6 地址族,但是没有找到 IPv6 地址,则返回 IPv4 映射的 IPv6 地址。在有些操作系统中不支持(例如 FreeBSD 10.1)。 * `dns.ALL`: 如果指定了 `dns.V4MAPPED`,则返回解析的 IPv6 地址以及 IPv4 映射的 IPv6 地址。 diff --git a/domain/domain.md b/domain/domain.md index 87857594..3bd21c51 100644 --- a/domain/domain.md +++ b/domain/domain.md @@ -15,6 +15,8 @@ changes: > Stability: 0 - Deprecated + + **This module is pending deprecation**. Once a replacement API has been finalized, this module will be fully deprecated. Most end users should **not** have cause to use this module. Users who absolutely must have diff --git a/domain/domains_and_promises.md b/domain/domains_and_promises.md index 70cc4f74..78fefd95 100644 --- a/domain/domains_and_promises.md +++ b/domain/domains_and_promises.md @@ -1,5 +1,5 @@ -As of Node.js 8.0.0, the handlers of Promises are run inside the domain in +As of Node.js 8.0.0, the handlers of promises are run inside the domain in which the call to `.then()` or `.catch()` itself was made: ```js @@ -37,7 +37,7 @@ d2.run(() => { ``` Domains will not interfere with the error handling mechanisms for -Promises. In other words, no `'error'` event will be emitted for unhandled +promises. In other words, no `'error'` event will be emitted for unhandled `Promise` rejections. diff --git a/errors/class_referenceerror.md b/errors/class_referenceerror.md index f2a573b9..116133c2 100644 --- a/errors/class_referenceerror.md +++ b/errors/class_referenceerror.md @@ -11,5 +11,5 @@ doesNotExist; // 抛出 ReferenceError,在这个程序中 doesNotExist 不是一个变量。 ``` -除非应用程序是动态地生成并运行代码,否则 `ReferenceError` 实例应该始终被视为代码中或其依赖中的错误。 +除非应用程序是动态地生成并运行代码,否则 `ReferenceError` 实例表示代码中或其依赖中的错误。 diff --git a/errors/class_typeerror.md b/errors/class_typeerror.md index e4e675c1..3b34114b 100644 --- a/errors/class_typeerror.md +++ b/errors/class_typeerror.md @@ -2,7 +2,7 @@ * 继承自 {errors.Error} 表明提供的参数不是被允许的类型。 -例如,将函数传给期望字符串的参数,将会被视为 `TypeError`。 +例如,将函数传给期望字符串的参数,则会抛出 `TypeError`。 ```js require('url').parse(() => { }); diff --git a/errors/err_entry_type_mismatch.md b/errors/err_entry_type_mismatch.md deleted file mode 100644 index f380ccdd..00000000 --- a/errors/err_entry_type_mismatch.md +++ /dev/null @@ -1,11 +0,0 @@ - -> Stability: 1 - Experimental - -The `--entry-type=commonjs` flag was used to attempt to execute an `.mjs` file -or a `.js` file where the nearest parent `package.json` contains -`"type": "module"`; or -the `--entry-type=module` flag was used to attempt to execute a `.cjs` file or -a `.js` file where the nearest parent `package.json` either lacks a `"type"` -field or contains `"type": "commonjs"`. - - diff --git a/errors/err_falsy_value_rejection.md b/errors/err_falsy_value_rejection.md index 61fd8273..e330fbd3 100644 --- a/errors/err_falsy_value_rejection.md +++ b/errors/err_falsy_value_rejection.md @@ -2,4 +2,4 @@ A `Promise` that was callbackified via `util.callbackify()` was rejected with a falsy value. - + diff --git a/errors/err_feature_unavailable_on_platform.md b/errors/err_feature_unavailable_on_platform.md index 3c0447d0..b333d2ae 100644 --- a/errors/err_feature_unavailable_on_platform.md +++ b/errors/err_feature_unavailable_on_platform.md @@ -1,5 +1,8 @@ + Used when a feature that is not available to the current platform which is running Node.js is used. - + diff --git a/errors/err_fs_watcher_already_started.md b/errors/err_fs_watcher_already_started.md deleted file mode 100644 index 1cd19977..00000000 --- a/errors/err_fs_watcher_already_started.md +++ /dev/null @@ -1,5 +0,0 @@ - -An attempt was made to start a watcher returned by `fs.watch()` that has -already been started. - - diff --git a/errors/err_fs_watcher_not_started.md b/errors/err_fs_watcher_not_started.md deleted file mode 100644 index d69584a1..00000000 --- a/errors/err_fs_watcher_not_started.md +++ /dev/null @@ -1,5 +0,0 @@ - -An attempt was made to initiate operations on a watcher returned by -`fs.watch()` that has not yet been started. - - diff --git a/errors/err_http2_already_shutdown.md b/errors/err_http2_already_shutdown.md deleted file mode 100644 index 2a8a179d..00000000 --- a/errors/err_http2_already_shutdown.md +++ /dev/null @@ -1,4 +0,0 @@ - -Occurs with multiple attempts to shutdown an HTTP/2 session. - - diff --git a/errors/err_http2_error_1.md b/errors/err_http2_error_1.md deleted file mode 100644 index 465fa9d2..00000000 --- a/errors/err_http2_error_1.md +++ /dev/null @@ -1,4 +0,0 @@ - -A non-specific HTTP/2 error has occurred. - - diff --git a/errors/err_invalid_repl_history.md b/errors/err_invalid_repl_history.md deleted file mode 100644 index c55b66b4..00000000 --- a/errors/err_invalid_repl_history.md +++ /dev/null @@ -1,5 +0,0 @@ - -Used in the `repl` in case the old history file is used and an error occurred -while trying to read and parse it. - - diff --git a/errors/err_invalid_repl_type.md b/errors/err_invalid_repl_type.md deleted file mode 100644 index f09e2d8c..00000000 --- a/errors/err_invalid_repl_type.md +++ /dev/null @@ -1,6 +0,0 @@ - -> Stability: 1 - Experimental - -The `--entry-type=...` flag is not compatible with the Node.js REPL. - - diff --git a/errors/err_out_of_range.md b/errors/err_out_of_range.md index a8976b01..dc03fbc1 100644 --- a/errors/err_out_of_range.md +++ b/errors/err_out_of_range.md @@ -1,4 +1,4 @@ A given value is out of the accepted range. - + diff --git a/errors/err_package_import_not_defined.md b/errors/err_package_import_not_defined.md new file mode 100644 index 00000000..75884329 --- /dev/null +++ b/errors/err_package_import_not_defined.md @@ -0,0 +1,5 @@ + +The `package.json` ["imports" field][] does not define the given internal +package specifier mapping. + + diff --git a/errors/err_stream_has_stringdecoder.md b/errors/err_stream_has_stringdecoder.md deleted file mode 100644 index 4734cb05..00000000 --- a/errors/err_stream_has_stringdecoder.md +++ /dev/null @@ -1,11 +0,0 @@ - -Used to prevent an abort if a string decoder was set on the Socket. - -```js -const Socket = require('net').Socket; -const instance = new Socket(); - -instance.setEncoding('utf8'); -``` - - diff --git a/errors/err_string_too_large.md b/errors/err_string_too_large.md deleted file mode 100644 index 9e3e47d0..00000000 --- a/errors/err_string_too_large.md +++ /dev/null @@ -1,5 +0,0 @@ - -An attempt has been made to create a string larger than the maximum allowed -size. - - diff --git a/errors/err_tty_writable_not_readable.md b/errors/err_tty_writable_not_readable.md deleted file mode 100644 index 7f6947ea..00000000 --- a/errors/err_tty_writable_not_readable.md +++ /dev/null @@ -1,77 +0,0 @@ - -This `Error` is thrown when a read is attempted on a TTY `WriteStream`, -such as `process.stdout.on('data')`. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/errors/err_zlib_binding_closed.md b/errors/err_zlib_binding_closed.md index c3e01e58..cc7aab96 100644 --- a/errors/err_zlib_binding_closed.md +++ b/errors/err_zlib_binding_closed.md @@ -6,3 +6,77 @@ removed: v10.0.0 Used when an attempt is made to use a `zlib` object after it has already been closed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/errors/error_code.md b/errors/error_code.md index 960ad23f..c6dee457 100644 --- a/errors/error_code.md +++ b/errors/error_code.md @@ -5,4 +5,4 @@ `error.code` 是识别错误的最稳定方法。 它只会在 Node.js 的主要版本之间更改。 相反,`error.message` 字符串可能会在 Node.js 的任何版本之间发生变化。 -详见 [Node.js 错误码][Node.js Error Codes]关于特定的错误码。 +详见 [Node.js 错误码][Node.js error codes]关于特定的错误码。 diff --git a/errors/other_error_codes.md b/errors/other_error_codes.md deleted file mode 100644 index 49c5ff5b..00000000 --- a/errors/other_error_codes.md +++ /dev/null @@ -1,5 +0,0 @@ - -These errors have never been released, but had been present on master between -releases. - - diff --git a/esm/approach_1_use_an_es_module_wrapper.md b/esm/approach_1_use_an_es_module_wrapper.md index d5309509..b044256e 100644 --- a/esm/approach_1_use_an_es_module_wrapper.md +++ b/esm/approach_1_use_an_es_module_wrapper.md @@ -1,7 +1,7 @@ Write the package in CommonJS or transpile ES module sources into CommonJS, and create an ES module wrapper file that defines the named exports. Using -[Conditional Exports][], the ES module wrapper is used for `import` and the +[Conditional exports][], the ES module wrapper is used for `import` and the CommonJS entry point for `require`. diff --git a/esm/code_resolve_code_hook.md b/esm/code_resolve_code_hook.md index e14c1898..a855837e 100644 --- a/esm/code_resolve_code_hook.md +++ b/esm/code_resolve_code_hook.md @@ -8,14 +8,15 @@ and parent URL. The module specifier is the string in an `import` statement or 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 +[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. +The current [package exports conditions][Conditional Exports] will always be in +the `context.conditions` array passed into the hook. To guarantee _default +Node.js module specifier resolution behavior_ when calling `defaultResolve`, the +`context.conditions` array passed to it _must_ include _all_ elements of the +`context.conditions` array originally passed into the `resolve` hook. ```js /** diff --git a/esm/commonjs_json_and_native_modules.md b/esm/commonjs_json_and_native_modules.md index c83ac6b7..6f9f4e8f 100644 --- a/esm/commonjs_json_and_native_modules.md +++ b/esm/commonjs_json_and_native_modules.md @@ -1,5 +1,5 @@ -CommonJS, JSON, and Native modules can be used with +CommonJS, JSON, and native modules can be used with [`module.createRequire()`][]. ```js diff --git a/esm/conditional_exports.md b/esm/conditional_exports.md index 4dc5d563..5e19ae5a 100644 --- a/esm/conditional_exports.md +++ b/esm/conditional_exports.md @@ -18,31 +18,33 @@ For example, a package that wants to provide different ES module exports for } ``` -Node.js supports the following conditions: +Node.js supports the following conditions out of the box: * `"import"` - matched when the package is loaded via `import` or `import()`. Can reference either an ES module or CommonJS file, as both `import` and `import()` can load either ES module or CommonJS sources. + _Always matched when the `"require"` condition is not matched._ * `"require"` - matched when the package is loaded via `require()`. As `require()` only supports CommonJS, the referenced file must be CommonJS. + _Always matched when the `"import"` condition is not matched._ * `"node"` - matched for any Node.js environment. Can be a CommonJS or ES module file. _This condition should always come after `"import"` or `"require"`._ * `"default"` - the generic fallback that will always match. Can be a CommonJS or ES module file. _This condition should always come last._ -Condition matching is applied in object order from first to last within the -`"exports"` object. _The general rule is that conditions should be used -from most specific to least specific in object order._ +Within the `"exports"` object, key order is significant. During condition +matching, earlier entries have higher priority and take precedence over later +entries. _The general rule is that conditions should be from most specific to +least specific in object order_. Other conditions such as `"browser"`, `"electron"`, `"deno"`, `"react-native"`, -etc. are ignored by Node.js but may be used by other runtimes or tools. -Further restrictions, definitions or guidance on condition names may be -provided in the future. +etc. are unknown to, and thus ignored by Node.js. Runtimes or tools other than +Node.js may use them at their discretion. Further restrictions, definitions, or +guidance on condition names may occur in the future. Using the `"import"` and `"require"` conditions can lead to some hazards, -which are explained further in -[the dual CommonJS/ES module packages section][]. +which are further explained in [the dual CommonJS/ES module packages section][]. Conditional exports can also be extended to exports subpaths, for example: @@ -53,7 +55,7 @@ Conditional exports can also be extended to exports subpaths, for example: "exports": { ".": "./main.js", "./feature": { - "browser": "./feature-browser.js", + "node": "./feature-node.js", "default": "./feature.js" } } @@ -61,6 +63,14 @@ Conditional exports can also be extended to exports subpaths, for example: ``` Defines a package where `require('pkg/feature')` and `import 'pkg/feature'` -could provide different implementations between the browser and Node.js, -given third-party tool support for a `"browser"` condition. +could provide different implementations between Node.js and other JS +environments. + +When using environment branches, always include a `"default"` condition where +possible. Providing a `"default"` condition ensures that any unknown JS +environments are able to use this universal implementation, which helps avoid +these JS environments from having to pretend to be existing environments in +order to support packages with conditional exports. For this reason, using +`"node"` and `"default"` condition branches is usually preferable to using +`"node"` and `"browser"` condition branches. diff --git a/esm/dual_commonjs_es_module_packages.md b/esm/dual_commonjs_es_module_packages.md index 2458c796..be934bd6 100644 --- a/esm/dual_commonjs_es_module_packages.md +++ b/esm/dual_commonjs_es_module_packages.md @@ -10,7 +10,7 @@ ignores) the top-level `"module"` field. Node.js can now run ES module entry points, and a package can contain both CommonJS and ES module entry points (either via separate specifiers such as `'pkg'` and `'pkg/es-module'`, or both at the same specifier via [Conditional -Exports][]). Unlike in the scenario where `"module"` is only used by bundlers, +exports][]). Unlike in the scenario where `"module"` is only used by bundlers, or ES module files are transpiled into CommonJS on the fly before evaluation by Node.js, the files referenced by the ES module entry point are evaluated as ES modules. diff --git a/esm/import_statements.md b/esm/import_statements.md index 5d5d5357..d9ab3fac 100644 --- a/esm/import_statements.md +++ b/esm/import_statements.md @@ -1,6 +1,6 @@ An `import` statement can reference an ES module or a CommonJS module. Other -file types such as JSON or Native modules are not supported. For those, use +file types such as JSON or native modules are not supported. For those, use [`module.createRequire()`][]. `import` statements are permitted only in ES modules. For similar functionality diff --git a/esm/internal_package_imports.md b/esm/internal_package_imports.md new file mode 100644 index 00000000..644bb8cf --- /dev/null +++ b/esm/internal_package_imports.md @@ -0,0 +1,36 @@ + +In addition to the `"exports"` field it is possible to define internal package +import maps that only apply to import specifiers from within the package itself. + +Entries in the imports field must always start with `#` to ensure they are +clearly disambiguated from package specifiers. + +For example, the imports field can be used to gain the benefits of conditional +exports for internal modules: + +```json +// package.json +{ + "imports": { + "#dep": { + "node": "dep-node-native", + "default": "./dep-polyfill.js" + } + }, + "dependencies": { + "dep-node-native": "^1.0.0" + } +} +``` + +where `import '#dep'` would now get the resolution of the external package +`dep-node-native` (including its exports in turn), and instead get the local +file `./dep-polyfill.js` relative to the package in other environments. + +Unlike the exports field, import maps permit mapping to external packages +because this provides an important use case for conditional loading and also can +be done without the risk of cycles, unlike for exports. + +Apart from the above, the resolution rules for the imports field are otherwise +analogous to the exports field. + diff --git a/esm/nested_conditions.md b/esm/nested_conditions.md index b24a3489..5036edc1 100644 --- a/esm/nested_conditions.md +++ b/esm/nested_conditions.md @@ -9,11 +9,11 @@ use in Node.js but not the browser: { "main": "./main.js", "exports": { - "browser": "./feature-browser.mjs", "node": { "import": "./feature-node.mjs", "require": "./feature-node.cjs" - } + }, + "default": "./feature.mjs", } } ``` diff --git a/esm/package_entry_points.md b/esm/package_entry_points.md index cac3422d..0125e050 100644 --- a/esm/package_entry_points.md +++ b/esm/package_entry_points.md @@ -17,7 +17,7 @@ CommonJS; `"main"` will be overridden by `"exports"` if it exists. As such fallback for legacy versions of Node.js that do not support the `"exports"` field. -[Conditional Exports][] can be used within `"exports"` to define different +[Conditional exports][] can be used within `"exports"` to define different package entry points per environment, including whether the package is referenced via `require` or via `import`. For more information about supporting both CommonJS and ES Modules in a single package please consult diff --git a/esm/package_scope_and_file_extensions.md b/esm/package_scope_and_file_extensions.md index f16c758f..7402f000 100644 --- a/esm/package_scope_and_file_extensions.md +++ b/esm/package_scope_and_file_extensions.md @@ -1,11 +1,11 @@ A folder containing a `package.json` file, and all subfolders below that folder -down until the next folder containing another `package.json`, is considered a -_package scope_. The `"type"` field defines how `.js` files should be treated -within a particular `package.json` file’s package scope. Every package in a +until the next folder containing another `package.json`, are a +_package scope_. The `"type"` field defines how to treat `.js` files +within the package scope. Every package in a 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"`. +project’s dependencies have their own package scopes. If a `package.json` file +does not have a `"type"` field, the default `"type"` is `"commonjs"`. 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. diff --git a/esm/resolver_algorithm.md b/esm/resolver_algorithm.md index d0144e81..00a1f44f 100644 --- a/esm/resolver_algorithm.md +++ b/esm/resolver_algorithm.md @@ -21,10 +21,11 @@ The resolver can throw the following errors: or package subpath specifier. * _Invalid Package Configuration_: package.json configuration is invalid or contains an invalid configuration. -* _Invalid Package Target_: Package exports define a target module within the - package that is an invalid type or string target. +* _Invalid Package Target_: Package exports or imports define a target module + for the package that is an invalid type or string target. * _Package Path Not Exported_: Package exports do not define or permit a target subpath in the package for the given module. +* _Package Import Not Defined_: Package imports do not define the specifier. * _Module Not Found_: The package or module requested does not exist.
@@ -36,11 +37,14 @@ The resolver can throw the following errors: > 1. If _specifier_ is a valid URL, then > 1. Set _resolvedURL_ to the result of parsing and reserializing > _specifier_ as a URL. -> 1. Otherwise, if _specifier_ starts with _"/"_, then -> 1. Throw an _Invalid Module Specifier_ error. -> 1. Otherwise, if _specifier_ starts with _"./"_ or _"../"_, then +> 1. Otherwise, if _specifier_ starts with _"/"_, _"./"_ or _"../"_, then > 1. Set _resolvedURL_ to the URL resolution of _specifier_ relative to > _parentURL_. +> 1. Otherwise, if _specifier_ starts with _"#"_, then +> 1. Set _resolvedURL_ to the result of +> **PACKAGE_INTERNAL_RESOLVE**(_specifier_, _parentURL_). +> 1. If _resolvedURL_ is **null** or **undefined**, throw a +> _Package Import Not Defined_ error. > 1. Otherwise, > 1. Note: _specifier_ is now a bare specifier. > 1. Set _resolvedURL_ the result of @@ -78,7 +82,7 @@ The resolver can throw the following errors: > 1. If _packageSubpath_ contains any _"."_ or _".."_ segments or percent > encoded strings for _"/"_ or _"\\"_, then > 1. Throw an _Invalid Module Specifier_ error. -> 1. Set _selfUrl_ to the result of +> 1. Let _selfUrl_ be the result of > **SELF_REFERENCE_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_). > 1. If _selfUrl_ isn't empty, return _selfUrl_. > 1. If _packageSubpath_ is _undefined_ and _packageName_ is a Node.js builtin @@ -101,8 +105,11 @@ The resolver can throw the following errors: > 1. If _pjson_ is not **null** and _pjson_ has an _"exports"_ key, then > 1. Let _exports_ be _pjson.exports_. > 1. If _exports_ is not **null** or **undefined**, then -> 1. Return **PACKAGE_EXPORTS_RESOLVE**(_packageURL_, -> _packageSubpath_, _pjson.exports_). +> 1. Let _resolved_ be the result of **PACKAGE_EXPORTS_RESOLVE**( +> _packageURL_, _packageSubpath_, _pjson.exports_). +> 1. If _resolved_ is **null** or **undefined**, throw a +> _Package Path Not Exported_ error. +> 1. Return _resolved_. > 1. Return the URL resolution of _packageSubpath_ in _packageURL_. > 1. Throw a _Module Not Found_ error. @@ -123,8 +130,11 @@ The resolver can throw the following errors: > 1. If _pjson_ is not **null** and _pjson_ has an _"exports"_ key, then > 1. Let _exports_ be _pjson.exports_. > 1. If _exports_ is not **null** or **undefined**, then -> 1. Return **PACKAGE_EXPORTS_RESOLVE**(_packageURL_, _subpath_, -> _pjson.exports_). +> 1. Let _resolved_ be the result of **PACKAGE_EXPORTS_RESOLVE**( +> _packageURL_, _subpath_, _pjson.exports_). +> 1. If _resolved_ is **null** or **undefined**, throw a +> _Package Path Not Exported_ error. +> 1. Return _resolved_. > 1. Return the URL resolution of _subpath_ in _packageURL_. > 1. Otherwise, return **undefined**. @@ -137,12 +147,18 @@ The resolver can throw the following errors: > not starting with _"."_, throw an _Invalid Package Configuration_ error. > 1. If _pjson.exports_ is a String or Array, or an Object containing no > keys starting with _"."_, then -> 1. Return **PACKAGE_EXPORTS_TARGET_RESOLVE**(_packageURL_, -> _pjson.exports_, _""_). +> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> _packageURL_, _pjson.exports_, _""_, **false**, _defaultEnv_). +> 1. If _resolved_ is **null** or **undefined**, throw a +> _Package Path Not Exported_ error. +> 1. Return _resolved_. > 1. If _pjson.exports_ is an Object containing a _"."_ property, then > 1. Let _mainExport_ be the _"."_ property in _pjson.exports_. -> 1. Return **PACKAGE_EXPORTS_TARGET_RESOLVE**(_packageURL_, -> _mainExport_, _""_). +> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> _packageURL_, _mainExport_, _""_, **false**, _defaultEnv_). +> 1. If _resolved_ is **null** or **undefined**, throw a +> _Package Path Not Exported_ error. +> 1. Return _resolved_. > 1. Throw a _Package Path Not Exported_ error. > 1. Let _legacyMainURL_ be the result applying the legacy > **LOAD_AS_DIRECTORY** CommonJS resolver to _packageURL_, throwing a @@ -156,8 +172,8 @@ The resolver can throw the following errors: > 1. Set _packagePath_ to _"./"_ concatenated with _packagePath_. > 1. If _packagePath_ is a key of _exports_, then > 1. Let _target_ be the value of _exports\[packagePath\]_. -> 1. Return **PACKAGE_EXPORTS_TARGET_RESOLVE**(_packageURL_, _target_, -> _""_, _defaultEnv_). +> 1. Return **PACKAGE_TARGET_RESOLVE**(_packageURL_, _target_, +> _""_, **false**, _defaultEnv_). > 1. Let _directoryKeys_ be the list of keys of _exports_ ending in > _"/"_, sorted by length descending. > 1. For each key _directory_ in _directoryKeys_, do @@ -165,22 +181,28 @@ The resolver can throw the following errors: > 1. Let _target_ be the value of _exports\[directory\]_. > 1. Let _subpath_ be the substring of _target_ starting at the index > of the length of _directory_. -> 1. Return **PACKAGE_EXPORTS_TARGET_RESOLVE**(_packageURL_, _target_, -> _subpath_, _defaultEnv_). -> 1. Throw a _Package Path Not Exported_ error. +> 1. Return **PACKAGE_TARGET_RESOLVE**(_packageURL_, _target_, +> _subpath_, **false**, _defaultEnv_). +> 1. Return **null**. -**PACKAGE_EXPORTS_TARGET_RESOLVE**(_packageURL_, _target_, _subpath_, _env_) +**PACKAGE_TARGET_RESOLVE**(_packageURL_, _target_, _subpath_, _internal_, _env_) > 1. If _target_ is a String, then -> 1. If _target_ does not start with _"./"_ or contains any _"node_modules"_ -> segments including _"node_modules"_ percent-encoding, throw an -> _Invalid Package Target_ error. +> 1. If _target_ contains any _"node_modules"_ segments including +> _"node_modules"_ percent-encoding, throw an _Invalid Package Target_ +> error. +> 1. If _subpath_ has non-zero length and _target_ does not end with _"/"_, +> throw an _Invalid Module Specifier_ error. +> 1. If _target_ does not start with _"./"_, then +> 1. If _target_ does not start with _"../"_ or _"/"_ and is not a valid +> URL, then +> 1. If _internal_ is **true**, return **PACKAGE_RESOLVE**( +> _target_ + _subpath_, _packageURL_ + _"/"_)_. +> 1. Otherwise throw an _Invalid Package Target_ error. > 1. Let _resolvedTarget_ be the URL resolution of the concatenation of > _packageURL_ and _target_. > 1. If _resolvedTarget_ is not contained in _packageURL_, throw an > _Invalid Package Target_ error. -> 1. If _subpath_ has non-zero length and _target_ does not end with _"/"_, -> throw an _Invalid Module Specifier_ error. > 1. Let _resolved_ be the URL resolution of the concatenation of > _subpath_ and _resolvedTarget_. > 1. If _resolved_ is not contained in _resolvedTarget_, throw an @@ -192,22 +214,48 @@ The resolver can throw the following errors: > 1. For each property _p_ of _target_, in object insertion order as, > 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 -> loop on any _Package Path Not Exported_ error. -> 1. Throw a _Package Path Not Exported_ error. +> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> _packageURL_, _targetValue_, _subpath_, _internal_, _env_) +> 1. If _resolved_ is equal to **undefined**, continue the loop. +> 1. Return _resolved_. +> 1. Return **undefined**. > 1. Otherwise, if _target_ is an Array, then -> 1. If _target.length is zero, throw a _Package Path Not Exported_ error. +> 1. If _target.length is zero, return **null**. > 1. For each item _targetValue_ in _target_, do -> 1. If _targetValue_ is an Array, continue the loop. -> 1. Return the result of **PACKAGE_EXPORTS_TARGET_RESOLVE**(_packageURL_, -> _targetValue_, _subpath_, _env_), continuing the loop on any -> _Package Path Not Exported_ or _Invalid Package Target_ error. -> 1. Throw the last fallback resolution error. -> 1. Otherwise, if _target_ is _null_, throw a _Package Path Not Exported_ -> error. +> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> _packageURL_, _targetValue_, _subpath_, _internal_, _env_), +> continuing the loop on any _Invalid Package Target_ error. +> 1. If _resolved_ is **undefined**, continue the loop. +> 1. Return _resolved_. +> 1. Return or throw the last fallback resolution **null** return or error. +> 1. Otherwise, if _target_ is _null_, return **null**. > 1. Otherwise throw an _Invalid Package Target_ error. +**PACKAGE_INTERNAL_RESOLVE**(_specifier_, _parentURL_) + +> 1. Assert: _specifier_ begins with _"#"_. +> 1. If _specifier_ is exactly equal to _"#"_ or starts with _"#/"_, then +> 1. Throw an _Invalid Module Specifier_ error. +> 1. Let _packageURL_ be the result of **READ_PACKAGE_SCOPE**(_parentURL_). +> 1. If _packageURL_ is not **null**, then +> 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_packageURL_). +> 1. If _pjson.imports is a non-null Object, then +> 1. Let _imports_ be _pjson.imports_. +> 1. If _specifier_ is a key of _imports_, then +> 1. Let _target_ be the value of _imports\[specifier\]_. +> 1. Return **PACKAGE_TARGET_RESOLVE**(_packageURL_, _target_, +> _""_, **true**, _defaultEnv_). +> 1. Let _directoryKeys_ be the list of keys of _imports_ ending in +> _"/"_, sorted by length descending. +> 1. For each key _directory_ in _directoryKeys_, do +> 1. If _specifier_ starts with _directory_, then +> 1. Let _target_ be the value of _imports\[directory\]_. +> 1. Let _subpath_ be the substring of _target_ starting at the +> index of the length of _directory_. +> 1. Return **PACKAGE_TARGET_RESOLVE**(_packageURL_, _target_, +> _subpath_, **true**, _defaultEnv_). +> 1. Return **null**. + **ESM_FORMAT**(_url_) > 1. Assert: _url_ corresponds to an existing file. diff --git a/events/awaiting_multiple_events_emitted_on_process_nexttick.md b/events/awaiting_multiple_events_emitted_on_process_nexttick.md new file mode 100644 index 00000000..88e8601b --- /dev/null +++ b/events/awaiting_multiple_events_emitted_on_process_nexttick.md @@ -0,0 +1,53 @@ + +There is an edge case worth noting when using the `events.once()` function +to await multiple events emitted on in the same batch of `process.nextTick()` +operations, or whenever multiple events are emitted synchronously. Specifically, +because the `process.nextTick()` queue is drained before the `Promise` microtask +queue, and because `EventEmitter` emits all events synchronously, it is possible +for `events.once()` to miss an event. + +```js +const { EventEmitter, once } = require('events'); + +const myEE = new EventEmitter(); + +async function foo() { + await once(myEE, 'bar'); + console.log('bar'); + + // This Promise will never resolve because the 'foo' event will + // have already been emitted before the Promise is created. + await once(myEE, 'foo'); + console.log('foo'); +} + +process.nextTick(() => { + myEE.emit('bar'); + myEE.emit('foo'); +}); + +foo().then(() => console.log('done')); +``` + +To catch both events, create each of the Promises *before* awaiting either +of them, then it becomes possible to use `Promise.all()`, `Promise.race()`, +or `Promise.allSettled()`: + +```js +const { EventEmitter, once } = require('events'); + +const myEE = new EventEmitter(); + +async function foo() { + await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]); + console.log('foo', 'bar'); +} + +process.nextTick(() => { + myEE.emit('bar'); + myEE.emit('foo'); +}); + +foo().then(() => console.log('done')); +``` + diff --git a/events/event_listener.md b/events/event_listener.md index c6b0f45f..8d4e5f08 100644 --- a/events/event_listener.md +++ b/events/event_listener.md @@ -7,7 +7,7 @@ passed to the `eventTarget.dispatchEvent()` function. Async functions may be used as event listeners. If an async handler function rejects, the rejection will be captured and be will handled as described in -[`EventTarget` Error Handling][]. +[`EventTarget` error handling][]. An error thrown by one handler function will not prevent the other handlers from being invoked. diff --git a/events/events.md b/events/events.md index 3e01b7bf..e1bbb810 100644 --- a/events/events.md +++ b/events/events.md @@ -5,6 +5,8 @@ + + 大多数 Node.js 核心 API 构建于惯用的异步事件驱动架构,其中某些类型的对象(又称触发器,Emitter)会触发命名事件来调用函数(又称监听器,Listener)。 例如,[`net.Server`] 会在每次有新连接时触发事件,[`fs.ReadStream`] 会在打开文件时触发事件,[stream]会在数据可读时触发事件。 diff --git a/events/events_once_emitter_name.md b/events/events_once_emitter_name.md index 09be7339..86e88c82 100644 --- a/events/events_once_emitter_name.md +++ b/events/events_once_emitter_name.md @@ -8,7 +8,7 @@ added: * `name` {string} * 返回: {Promise} -创建一个 `Promise`,当 `EventEmitter` 触发给定的事件时则会被解决,当 `EventEmitter` 触发 `'error'` 时则会被拒绝。 +创建一个 `Promise`,当 `EventEmitter` 触发给定的事件时则会被解决,如果等待时 `EventEmitter` 触发 `'error'` 则会被拒绝。 解决 `Promise` 时将会带上触发到给定事件的所有参数的数组。 此方法是有意通用的,并且可与 Web 平台的 [EventTarget][WHATWG-EventTarget] 接口一起使用,该接口没有特殊的 `'error'` 事件语义且不监听 `'error'` 事件。 @@ -41,13 +41,22 @@ async function run() { run(); ``` +The special handling of the `'error'` event is only used when `events.once()` +is used to wait for another event. If `events.once()` is used to wait for the +'`error'` event itself, then it is treated as any other kind of event without +special handling: +```js +const { EventEmitter, once } = require('events'); +const ee = new EventEmitter(); +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch((err) => console.log('error', err.message)); +ee.emit('error', new Error('boom')); - - - - +// Prints: ok boom +``` diff --git a/events/node_js_eventtarget_vs_dom_eventtarget.md b/events/node_js_eventtarget_vs_dom_eventtarget.md index f42ffd5d..f40550a6 100644 --- a/events/node_js_eventtarget_vs_dom_eventtarget.md +++ b/events/node_js_eventtarget_vs_dom_eventtarget.md @@ -10,5 +10,5 @@ There are two key differences between the Node.js `EventTarget` and the 2. In the Node.js `EventTarget`, if an event listener is an async function or returns a `Promise`, and the returned `Promise` rejects, the rejection will be automatically captured and handled the same way as a listener that - throws synchronously (see [`EventTarget` Error Handling][] for details). + throws synchronously (see [`EventTarget` error handling][] for details). diff --git a/fs/class_fs_readstream.md b/fs/class_fs_readstream.md index 02e3f3c8..37fe6824 100644 --- a/fs/class_fs_readstream.md +++ b/fs/class_fs_readstream.md @@ -4,6 +4,6 @@ added: v0.1.93 * 继承自: {stream.Readable} -成功调用 `fs.createReadStream()` 会返回新建的 `fs.ReadStream` 对象。 +使用 [`fs.createReadStream()`] 函数创建并返回的 `fs.ReadStream` 实例。 diff --git a/fs/class_fs_writestream.md b/fs/class_fs_writestream.md index 86429796..a776864b 100644 --- a/fs/class_fs_writestream.md +++ b/fs/class_fs_writestream.md @@ -4,3 +4,4 @@ added: v0.1.93 * 继承自 {stream.Writable} +使用 [`fs.createWriteStream()`] 函数创建并返回的 `fs.WriteStream` 实例。 diff --git a/fs/file_system.md b/fs/file_system.md index d7b00126..ba1cbc05 100644 --- a/fs/file_system.md +++ b/fs/file_system.md @@ -5,6 +5,8 @@ + + `fs` 模块提供了用于与文件系统进行交互(以类似于标准 POSIX 函数的方式)的 API。 要使用此模块: @@ -71,12 +73,11 @@ fs.rename('旧文件', '新文件', (err) => { 在繁忙的进程中,应使用这些调用的异步版本。 同步的版本会阻塞整个进程(停止所有的连接),直到它们完成。 -虽然不建议这样做,但是大多数 fs 函数都可以省略回调参数,在这种情况下,会使用默认的回调来抛出错误。 +大多数异步的 `fs` 函数都可以省略回调参数。 +但是,不建议这么使用。 +当省略回调时,会使用默认的回调来抛出错误。 若要获取对原始调用点的跟踪,则设置 `NODE_DEBUG` 环境变量: -不建议省略异步的 fs 函数上的回调函数,因为将来可能会抛出错误。 - - ```console $ cat script.js function bad() { diff --git a/fs/file_system_flags.md b/fs/file_system_flags.md index ce5f28dc..177029d3 100644 --- a/fs/file_system_flags.md +++ b/fs/file_system_flags.md @@ -46,8 +46,8 @@ 常用的常量可以从 `fs.constants` 获取。 在 Windows 上,标志会被转换为合适的等效标志,例如 `O_WRONLY` 转换为 `FILE_GENERIC_WRITE`、`O_EXCL|O_CREAT` 转换为能被 `CreateFileW` 接受的 `CREATE_NEW`。 -排他性标志 `'x'`( open(2) 中的 `O_EXCL` 标志)可以确保路径是新创建的。 -在 POSIX 系统上,即使路径是符号链接(指向不存在的文件),该路径也会被视为存在。 +如果路径已经存在,则排他性标志 `'x'`( open(2) 中的 `O_EXCL` 标志)会使操作返回错误。 +在 POSIX 上,如果路径是符号链接,则使用 `O_EXCL` 也会返回错误(即使符号链接指向不存在的路径)。 排他性标志不一定适用于网络文件系统。 在 Linux 上,当以追加模式打开文件时,则写入时无法指定位置。 diff --git a/fs/fs_access_path_mode_callback.md b/fs/fs_access_path_mode_callback.md index fc2aa07f..8d2bcd85 100644 --- a/fs/fs_access_path_mode_callback.md +++ b/fs/fs_access_path_mode_callback.md @@ -18,7 +18,7 @@ changes: 测试用户对 `path` 指定的文件或目录的权限。 `mode` 参数是一个可选的整数,指定要执行的可访问性检查。 -查看[文件可访问性的常量][File Access Constants]了解 `mode` 的可选值。 +查看[文件可访问性的常量][File access constants]了解 `mode` 的可选值。 可以创建由两个或更多个值按位或组成的掩码(例如 `fs.constants.W_OK | fs.constants.R_OK`)。 最后一个参数 `callback` 是回调函数,调用时会传入可能的错误参数。 diff --git a/fs/fs_accesssync_path_mode.md b/fs/fs_accesssync_path_mode.md index 4a758e6a..02297fd8 100644 --- a/fs/fs_accesssync_path_mode.md +++ b/fs/fs_accesssync_path_mode.md @@ -12,7 +12,7 @@ changes: 同步地测试用户对 `path` 指定的文件或目录的权限。 `mode` 参数是一个可选的整数,指定要执行的可访问性检查。 -查看[文件可访问性的常量][File Access Constants]了解 `mode` 的可选值。 +查看[文件可访问性的常量][File access constants]了解 `mode` 的可选值。 可以创建由两个或更多个值按位或组成的掩码(例如 `fs.constants.W_OK | fs.constants.R_OK`)。 如果可访问性检查失败,则抛出 `Error`。 diff --git a/fs/fs_constants.md b/fs/fs_constants.md index 38fbcf8b..20dd58ac 100644 --- a/fs/fs_constants.md +++ b/fs/fs_constants.md @@ -2,5 +2,5 @@ * {Object} 返回包含文件系统操作常用常量的对象。 -当前定义的特定常量在 [FS 常量][FS Constants]中描述。 +当前定义的特定常量在 [FS 常量][FS constants]中描述。 diff --git a/fs/fspromises_access_path_mode.md b/fs/fspromises_access_path_mode.md index f6487d13..42962699 100644 --- a/fs/fspromises_access_path_mode.md +++ b/fs/fspromises_access_path_mode.md @@ -8,7 +8,7 @@ added: v10.0.0 测试用户对 `path` 指定的文件或目录的权限。 `mode` 参数是一个可选的整数,指定要执行的可访问性检查。 -查看[文件可访问性的常量][File Access Constants]了解 `mode` 的可选值。 +查看[文件可访问性的常量][File access constants]了解 `mode` 的可选值。 可以创建由两个或更多个值按位或组成的掩码(例如 `fs.constants.W_OK | fs.constants.R_OK`)。 如果可访问性检查成功,则 `Promise` 会被解决且不带值。 diff --git a/fs/stats_rdev.md b/fs/stats_rdev.md index de64e340..386256fb 100644 --- a/fs/stats_rdev.md +++ b/fs/stats_rdev.md @@ -1,5 +1,5 @@ * {number|bigint} -如果文件被视为特殊文件,则此值为数字型设备标识符。 +如果文件表示一个设备,则此值为数字型设备标识符。 diff --git a/http/http.md b/http/http.md index 0dee5766..15a4f267 100644 --- a/http/http.md +++ b/http/http.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + 若要使用 HTTP 服务器和客户端,则可以 `require('http')`。 Node.js 中的 HTTP 接口旨在支持许多传统上难以使用的协议的特性。 diff --git a/http/http_get_url_options_callback.md b/http/http_get_url_options_callback.md index a0c57b41..643c44de 100644 --- a/http/http_get_url_options_callback.md +++ b/http/http_get_url_options_callback.md @@ -29,6 +29,7 @@ http.get('http://nodejs.org/dist/index.json', (res) => { const contentType = res.headers['content-type']; let error; + // 任何 2xx 状态码都表示成功的响应,但是这里只检查 200。 if (statusCode !== 200) { error = new Error('请求失败\n' + `状态码: ${statusCode}`); diff --git a/http/message_url.md b/http/message_url.md index 6f32ecf1..d334cfc5 100644 --- a/http/message_url.md +++ b/http/message_url.md @@ -8,12 +8,11 @@ added: v0.1.90 请求的 URL 字符串。 它仅包含实际的 HTTP 请求中存在的 URL。 -如果请求是: +以下面的请求为例: ```http -GET /status?name=ryan HTTP/1.1\r\n -Accept: text/plain\r\n -\r\n +GET /status?name=ryan HTTP/1.1 +Accept: text/plain ``` 要将 URL 解析成各个部分: diff --git a/http/new_agent_options.md b/http/new_agent_options.md index a49fe5d7..80508a74 100644 --- a/http/new_agent_options.md +++ b/http/new_agent_options.md @@ -1,6 +1,9 @@ + +The `'ready'` event is emitted when the `Http2Stream` has been opened, has +been assigned an `id`, and can be used. The listener does not expect any +arguments. + diff --git a/http2/event_stream.md b/http2/event_stream.md index d63f75e8..19451a79 100644 --- a/http2/event_stream.md +++ b/http2/event_stream.md @@ -18,7 +18,7 @@ session.on('stream', (stream, headers, flags) => { // ... stream.respond({ ':status': 200, - 'content-type': 'text/plain' + 'content-type': 'text/plain; charset=utf-8' }); stream.write('hello '); stream.end('world'); @@ -38,7 +38,7 @@ const server = http2.createServer(); server.on('stream', (stream, headers) => { stream.respond({ - 'content-type': 'text/html', + 'content-type': 'text/html; charset=utf-8', ':status': 200 }); stream.on('error', (error) => console.error(error)); diff --git a/http2/event_stream_1.md b/http2/event_stream_1.md index 40e6a799..23964b43 100644 --- a/http2/event_stream_1.md +++ b/http2/event_stream_1.md @@ -21,7 +21,7 @@ server.on('stream', (stream, headers, flags) => { // ... stream.respond({ [HTTP2_HEADER_STATUS]: 200, - [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' + [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8' }); stream.write('hello '); stream.end('world'); diff --git a/http2/event_stream_2.md b/http2/event_stream_2.md index 626521fe..35d541cb 100644 --- a/http2/event_stream_2.md +++ b/http2/event_stream_2.md @@ -23,7 +23,7 @@ server.on('stream', (stream, headers, flags) => { // ... stream.respond({ [HTTP2_HEADER_STATUS]: 200, - [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' + [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8' }); stream.write('hello '); stream.end('world'); diff --git a/http2/http2_createsecureserver_options_onrequesthandler.md b/http2/http2_createsecureserver_options_onrequesthandler.md index 31fc9336..17ba34f7 100644 --- a/http2/http2_createsecureserver_options_onrequesthandler.md +++ b/http2/http2_createsecureserver_options_onrequesthandler.md @@ -114,7 +114,7 @@ const server = http2.createSecureServer(options); server.on('stream', (stream, headers) => { stream.respond({ - 'content-type': 'text/html', + 'content-type': 'text/html; charset=utf-8', ':status': 200 }); stream.end('

Hello World

'); diff --git a/http2/http2_createserver_options_onrequesthandler.md b/http2/http2_createserver_options_onrequesthandler.md index 960d00fa..1cf4739f 100644 --- a/http2/http2_createserver_options_onrequesthandler.md +++ b/http2/http2_createserver_options_onrequesthandler.md @@ -127,7 +127,7 @@ const server = http2.createServer(); server.on('stream', (stream, headers) => { stream.respond({ - 'content-type': 'text/html', + 'content-type': 'text/html; charset=utf-8', ':status': 200 }); stream.end('

Hello World

'); diff --git a/http2/http2stream_respondwithfd_fd_headers_options.md b/http2/http2stream_respondwithfd_fd_headers_options.md index b64f3f4c..05881ebc 100644 --- a/http2/http2stream_respondwithfd_fd_headers_options.md +++ b/http2/http2stream_respondwithfd_fd_headers_options.md @@ -42,7 +42,7 @@ server.on('stream', (stream) => { const headers = { 'content-length': stat.size, 'last-modified': stat.mtime.toUTCString(), - 'content-type': 'text/plain' + 'content-type': 'text/plain; charset=utf-8' }; stream.respondWithFD(fd, headers); stream.on('close', () => fs.closeSync(fd)); @@ -87,7 +87,7 @@ server.on('stream', (stream) => { const headers = { 'content-length': stat.size, 'last-modified': stat.mtime.toUTCString(), - 'content-type': 'text/plain' + 'content-type': 'text/plain; charset=utf-8' }; stream.respondWithFD(fd, headers, { waitForTrailers: true }); stream.on('wantTrailers', () => { diff --git a/http2/http2stream_respondwithfile_path_headers_options.md b/http2/http2stream_respondwithfile_path_headers_options.md index 0d78a1de..64727050 100644 --- a/http2/http2stream_respondwithfile_path_headers_options.md +++ b/http2/http2stream_respondwithfile_path_headers_options.md @@ -56,7 +56,7 @@ server.on('stream', (stream) => { } stream.respondWithFile('/some/file', - { 'content-type': 'text/plain' }, + { 'content-type': 'text/plain; charset=utf-8' }, { statCheck, onError }); }); ``` @@ -76,7 +76,7 @@ server.on('stream', (stream) => { return false; // Cancel the send operation } stream.respondWithFile('/some/file', - { 'content-type': 'text/plain' }, + { 'content-type': 'text/plain; charset=utf-8' }, { statCheck }); }); ``` @@ -106,7 +106,7 @@ const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respondWithFile('/some/file', - { 'content-type': 'text/plain' }, + { 'content-type': 'text/plain; charset=utf-8' }, { waitForTrailers: true }); stream.on('wantTrailers', () => { stream.sendTrailers({ ABC: 'some value to send' }); diff --git a/http2/http_2.md b/http2/http_2.md index 1958d40c..6887ff58 100644 --- a/http2/http_2.md +++ b/http2/http_2.md @@ -9,6 +9,8 @@ changes: > 稳定性: 2 - 稳定 + + `http2` 模块提供了 [HTTP/2] 协议的实现。 使用方法如下: diff --git a/http2/request_url.md b/http2/request_url.md index 921a112a..f79275cd 100644 --- a/http2/request_url.md +++ b/http2/request_url.md @@ -4,13 +4,12 @@ added: v8.4.0 * {string} -Request URL string. This contains only the URL that is -present in the actual HTTP request. If the request is: +Request URL string. This contains only the URL that is present in the actual +HTTP request. If the request is: ```http -GET /status?name=ryan HTTP/1.1\r\n -Accept: text/plain\r\n -\r\n +GET /status?name=ryan HTTP/1.1 +Accept: text/plain ``` Then `request.url` will be: @@ -20,7 +19,7 @@ Then `request.url` will be: '/status?name=ryan' ``` -To parse the url into its parts `require('url').parse(request.url)` +To parse the url into its parts, `require('url').parse(request.url)` can be used: ```console diff --git a/http2/response_setheader_name_value.md b/http2/response_setheader_name_value.md index 0e8af9f6..cc21a77a 100644 --- a/http2/response_setheader_name_value.md +++ b/http2/response_setheader_name_value.md @@ -10,7 +10,7 @@ in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name. ```js -response.setHeader('Content-Type', 'text/html'); +response.setHeader('Content-Type', 'text/html; charset=utf-8'); ``` or @@ -29,9 +29,9 @@ to [`response.writeHead()`][] given precedence. ```js // Returns content-type = text/plain const server = http2.createServer((req, res) => { - res.setHeader('Content-Type', 'text/html'); + res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.setHeader('X-Foo', 'bar'); - res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('ok'); }); ``` diff --git a/http2/response_writehead_statuscode_statusmessage_headers.md b/http2/response_writehead_statuscode_statusmessage_headers.md index 53a29ca3..ebb71292 100644 --- a/http2/response_writehead_statuscode_statusmessage_headers.md +++ b/http2/response_writehead_statuscode_statusmessage_headers.md @@ -28,7 +28,7 @@ will be emitted. const body = 'hello world'; response.writeHead(200, { 'Content-Length': Buffer.byteLength(body), - 'Content-Type': 'text/plain' }); + 'Content-Type': 'text/plain; charset=utf-8' }); ``` `Content-Length` is given in bytes not characters. The @@ -51,9 +51,9 @@ to [`response.writeHead()`][] given precedence. ```js // Returns content-type = text/plain const server = http2.createServer((req, res) => { - res.setHeader('Content-Type', 'text/html'); + res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.setHeader('X-Foo', 'bar'); - res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('ok'); }); ``` diff --git a/http2/server_side_example.md b/http2/server_side_example.md index e2f3ba4c..dfdfc468 100644 --- a/http2/server_side_example.md +++ b/http2/server_side_example.md @@ -15,7 +15,7 @@ server.on('error', (err) => console.error(err)); server.on('stream', (stream, headers) => { // 流是一个双工流。 stream.respond({ - 'content-type': 'text/html', + 'content-type': 'text/html; charset=utf-8', ':status': 200 }); stream.end('

你好世界

'); diff --git a/https/https.md b/https/https.md index 10f16e85..4fa17652 100644 --- a/https/https.md +++ b/https/https.md @@ -3,5 +3,7 @@ > 稳定性: 2 - 稳定 + + HTTPS 是基于 TLS/SSL 的 HTTP 协议。在 Node.js 中,其被实现为一个单独的模块。 diff --git a/inspector/inspector.md b/inspector/inspector.md index 832d867c..0aede7b7 100644 --- a/inspector/inspector.md +++ b/inspector/inspector.md @@ -3,6 +3,8 @@ > Stability: 1 - Experimental + + The `inspector` module provides an API for interacting with the V8 inspector. It can be accessed using: diff --git a/modules/all_together.md b/modules/all_together.md index 3b693251..3c99fa37 100644 --- a/modules/all_together.md +++ b/modules/all_together.md @@ -16,7 +16,9 @@ require(X) from module at path Y a. LOAD_AS_FILE(Y + X) b. LOAD_AS_DIRECTORY(Y + X) c. THROW "not found" -4. LOAD_SELF_REFERENCE(X, dirname(Y)) +4. If X begins with '#' + a. LOAD_INTERAL_IMPORT(X, Y) +4. LOAD_SELF_REFERENCE(X, Y) 5. LOAD_NODE_MODULES(X, dirname(Y)) 6. THROW "not found" @@ -92,5 +94,14 @@ LOAD_PACKAGE_EXPORTS(DIR, X) 12. Otherwise a. If RESOLVED is a file, load it as its file extension format. STOP 13. Throw "not found" + +LOAD_INTERNAL_IMPORT(X, START) +1. Find the closest package scope to START. +2. If no scope was found or the `package.json` has no "imports", return. +3. let RESOLVED = + fileURLToPath(PACKAGE_INTERNAL_RESOLVE(X, pathToFileURL(START)), as defined + in the ESM resolver. +4. If RESOLVED is not a valid file, throw "not found" +5. Load RESOLVED as its file extension format. STOP ``` diff --git a/modules/module_parent.md b/modules/module_parent.md index bbcbb80b..8325086a 100644 --- a/modules/module_parent.md +++ b/modules/module_parent.md @@ -1,8 +1,14 @@ -* {module} +> Stability: 0 - Deprecated: Please use [`require.main`][] and +> [`module.children`][] instead. -最先引用该模块的模块。 +* {module | null | undefined} + +The module that first required this one, or `null` if the current module is the +entry point of the current process, or `undefined` if the module was loaded by +something that is not a CommonJS module (E.G.: REPL or `import`). diff --git a/modules/new_sourcemap_payload.md b/modules/new_sourcemap_payload.md index 021b278b..bf54b70e 100644 --- a/modules/new_sourcemap_payload.md +++ b/modules/new_sourcemap_payload.md @@ -3,7 +3,7 @@ Creates a new `sourceMap` instance. -`payload` is an object with keys matching the [Source Map V3 format][]: +`payload` is an object with keys matching the [Source map v3 format][]: * `file`: {string} * `version`: {number} diff --git a/modules/sourcemap_findentry_linenumber_columnnumber.md b/modules/sourcemap_findentry_linenumber_columnnumber.md index 4e896384..f762c3a4 100644 --- a/modules/sourcemap_findentry_linenumber_columnnumber.md +++ b/modules/sourcemap_findentry_linenumber_columnnumber.md @@ -30,6 +30,8 @@ consists of the following keys: + + diff --git a/n-api/module_registration.md b/n-api/module_registration.md index e027249e..42bac791 100644 --- a/n-api/module_registration.md +++ b/n-api/module_registration.md @@ -46,7 +46,7 @@ napi_value Init(napi_env env, napi_value exports) { ``` To define a class so that new instances can be created (often used with -[Object Wrap][]): +[Object wrap][]): ```c // NOTE: partial example, not all referenced code is included @@ -103,7 +103,7 @@ The variables `env` and `exports` will be available inside the function body following the macro invocation. For more details on setting properties on objects, see the section on -[Working with JavaScript Properties][]. +[Working with JavaScript properties][]. For more details on building addon modules in general, refer to the existing API. diff --git a/n-api/n_api.md b/n-api/n_api.md index e051ddfd..87d0f262 100644 --- a/n-api/n_api.md +++ b/n-api/n_api.md @@ -30,7 +30,7 @@ properties: `napi_value`. * In case of an error status code, additional information can be obtained using `napi_get_last_error_info`. More information can be found in the error - handling section [Error Handling][]. + handling section [Error handling][]. The N-API is a C API that ensures ABI stability across Node.js versions and different compiler levels. A C++ API can be easier to use. diff --git a/n-api/n_api_callback_types.md b/n-api/n_api_callback_types.md index e69de29b..8b137891 100644 --- a/n-api/n_api_callback_types.md +++ b/n-api/n_api_callback_types.md @@ -0,0 +1 @@ + diff --git a/n-api/napi_add_finalizer.md b/n-api/napi_add_finalizer.md index cb03edfb..145af822 100644 --- a/n-api/napi_add_finalizer.md +++ b/n-api/napi_add_finalizer.md @@ -20,6 +20,7 @@ napi_status napi_add_finalizer(napi_env env, object. * `[in] finalize_cb`: Native callback that will be used to free the native data when the JavaScript object is ready for garbage-collection. + [`napi_finalize`][] provides more details. * `[in] finalize_hint`: Optional contextual hint that is passed to the finalize callback. * `[out] result`: Optional reference to the JavaScript object. diff --git a/n-api/napi_async_complete_callback.md b/n-api/napi_async_complete_callback.md index 93ffcb32..1e6a7119 100644 --- a/n-api/napi_async_complete_callback.md +++ b/n-api/napi_async_complete_callback.md @@ -11,3 +11,6 @@ typedef void (*napi_async_complete_callback)(napi_env env, void* data); ``` +Unless for reasons discussed in [Object Lifetime Management][], creating a +handle and/or callback scope inside the function body is not necessary. + diff --git a/n-api/napi_async_execute_callback.md b/n-api/napi_async_execute_callback.md index 580058f4..04666344 100644 --- a/n-api/napi_async_execute_callback.md +++ b/n-api/napi_async_execute_callback.md @@ -9,10 +9,8 @@ operations. Callback functions must satisfy the following signature: typedef void (*napi_async_execute_callback)(napi_env env, void* data); ``` -Implementations of this function must avoid making N-API calls -that execute JavaScript or interact with -JavaScript objects. N-API -calls should be in the `napi_async_complete_callback` instead. -Do not use the `napi_env` parameter as it will likely -result in execution of JavaScript. +Implementations of this function must avoid making N-API calls that execute +JavaScript or interact with JavaScript objects. N-API calls should be in the +`napi_async_complete_callback` instead. Do not use the `napi_env` parameter as +it will likely result in execution of JavaScript. diff --git a/n-api/napi_callback.md b/n-api/napi_callback.md index 1cacc47b..8ed89ce9 100644 --- a/n-api/napi_callback.md +++ b/n-api/napi_callback.md @@ -10,3 +10,6 @@ following signature: typedef napi_value (*napi_callback)(napi_env, napi_callback_info); ``` +Unless for reasons discussed in [Object Lifetime Management][], creating a +handle and/or callback scope inside a `napi_callback` is not necessary. + diff --git a/n-api/napi_create_async_work.md b/n-api/napi_create_async_work.md index d02957f1..8deb20aa 100644 --- a/n-api/napi_create_async_work.md +++ b/n-api/napi_create_async_work.md @@ -27,7 +27,8 @@ napi_status napi_create_async_work(napi_env env, and can execute in parallel with the main event loop thread. * `[in] complete`: The native function which will be called when the asynchronous logic is completed or is cancelled. The given function is called - from the main event loop thread. + from the main event loop thread. [`napi_async_complete_callback`][] provides + more details. * `[in] data`: User-provided data context. This will be passed back into the execute and complete functions. * `[out] result`: `napi_async_work*` which is the handle to the newly created diff --git a/n-api/napi_create_external.md b/n-api/napi_create_external.md index 8dd285ff..deb1621a 100644 --- a/n-api/napi_create_external.md +++ b/n-api/napi_create_external.md @@ -14,7 +14,7 @@ napi_status napi_create_external(napi_env env, * `[in] env`: The environment that the API is invoked under. * `[in] data`: Raw pointer to the external data. * `[in] finalize_cb`: Optional callback to call when the external value is being - collected. + collected. [`napi_finalize`][] provides more details. * `[in] finalize_hint`: Optional hint to pass to the finalize callback during collection. * `[out] result`: A `napi_value` representing an external value. diff --git a/n-api/napi_create_external_arraybuffer.md b/n-api/napi_create_external_arraybuffer.md index 4a26617c..c2b53e44 100644 --- a/n-api/napi_create_external_arraybuffer.md +++ b/n-api/napi_create_external_arraybuffer.md @@ -18,7 +18,7 @@ napi_create_external_arraybuffer(napi_env env, `ArrayBuffer`. * `[in] byte_length`: The length in bytes of the underlying buffer. * `[in] finalize_cb`: Optional callback to call when the `ArrayBuffer` is being - collected. + collected. [`napi_finalize`][] provides more details. * `[in] finalize_hint`: Optional hint to pass to the finalize callback during collection. * `[out] result`: A `napi_value` representing a JavaScript `ArrayBuffer`. diff --git a/n-api/napi_create_external_buffer.md b/n-api/napi_create_external_buffer.md index 33cbf306..00621bb1 100644 --- a/n-api/napi_create_external_buffer.md +++ b/n-api/napi_create_external_buffer.md @@ -15,9 +15,9 @@ napi_status napi_create_external_buffer(napi_env env, * `[in] env`: The environment that the API is invoked under. * `[in] length`: Size in bytes of the input buffer (should be the same as the size of the new buffer). -* `[in] data`: Raw pointer to the underlying buffer to copy from. +* `[in] data`: Raw pointer to the underlying buffer to expose to JavaScript. * `[in] finalize_cb`: Optional callback to call when the `ArrayBuffer` is being - collected. + collected. [`napi_finalize`][] provides more details. * `[in] finalize_hint`: Optional hint to pass to the finalize callback during collection. * `[out] result`: A `napi_value` representing a `node::Buffer`. diff --git a/n-api/napi_create_function.md b/n-api/napi_create_function.md index f2661c00..876ba6e2 100644 --- a/n-api/napi_create_function.md +++ b/n-api/napi_create_function.md @@ -18,7 +18,7 @@ napi_status napi_create_function(napi_env env, * `[in] length`: The length of the `utf8name` in bytes, or `NAPI_AUTO_LENGTH` if it is null-terminated. * `[in] cb`: The native function which should be called when this function - object is invoked. + object is invoked. [`napi_callback`][] provides more details. * `[in] data`: User-provided data context. This will be passed back into the function when invoked later. * `[out] result`: `napi_value` representing the JavaScript function object for diff --git a/n-api/napi_create_threadsafe_function.md b/n-api/napi_create_threadsafe_function.md index 67b1ebd0..6dbaa648 100644 --- a/n-api/napi_create_threadsafe_function.md +++ b/n-api/napi_create_threadsafe_function.md @@ -46,5 +46,6 @@ napi_create_threadsafe_function(napi_env env, response to a call on a different thread. This callback will be called on the main thread. If not given, the JavaScript function will be called with no parameters and with `undefined` as its `this` value. + [`napi_threadsafe_function_call_js`][] provides more details. * `[out] result`: The asynchronous thread-safe JavaScript function. diff --git a/n-api/napi_define_class.md b/n-api/napi_define_class.md index 40b8aaa0..27fafb93 100644 --- a/n-api/napi_define_class.md +++ b/n-api/napi_define_class.md @@ -21,8 +21,8 @@ napi_status napi_define_class(napi_env env, * `[in] length`: The length of the `utf8name` in bytes, or `NAPI_AUTO_LENGTH` if it is null-terminated. * `[in] constructor`: Callback function that handles constructing instances - of the class. (This should be a static method on the class, not an actual - C++ constructor function.) + of the class. This should be a static method on the class, not an actual + C++ constructor function. [`napi_callback`][] provides more details. * `[in] data`: Optional data to be passed to the constructor callback as the `data` property of the callback info. * `[in] property_count`: Number of items in the `properties` array argument. diff --git a/n-api/napi_extended_error_info.md b/n-api/napi_extended_error_info.md index db9c1a06..99e41cf8 100644 --- a/n-api/napi_extended_error_info.md +++ b/n-api/napi_extended_error_info.md @@ -20,5 +20,5 @@ typedef struct { not implemented for any VM. * `error_code`: The N-API status code that originated with the last error. -See the [Error Handling][] section for additional information. +See the [Error handling][] section for additional information. diff --git a/n-api/napi_finalize.md b/n-api/napi_finalize.md index 3e4d9c98..2eda4023 100644 --- a/n-api/napi_finalize.md +++ b/n-api/napi_finalize.md @@ -15,3 +15,6 @@ typedef void (*napi_finalize)(napi_env env, void* finalize_hint); ``` +Unless for reasons discussed in [Object Lifetime Management][], creating a +handle and/or callback scope inside the function body is not necessary. + diff --git a/n-api/napi_handle_scope.md b/n-api/napi_handle_scope.md index c879af5c..fd69e64a 100644 --- a/n-api/napi_handle_scope.md +++ b/n-api/napi_handle_scope.md @@ -14,5 +14,5 @@ using [`napi_close_handle_scope`][]. Closing the scope can indicate to the GC that all `napi_value`s created during the lifetime of the handle scope are no longer referenced from the current stack frame. -For more details, review the [Object Lifetime Management][]. +For more details, review the [Object lifetime management][]. diff --git a/n-api/napi_property_descriptor.md b/n-api/napi_property_descriptor.md index 18d43eaf..65a95f81 100644 --- a/n-api/napi_property_descriptor.md +++ b/n-api/napi_property_descriptor.md @@ -28,16 +28,16 @@ typedef struct { If this is passed in, set `value` and `method` to `NULL` (since these members won't be used). The given function is called implicitly by the runtime when the property is accessed from JavaScript code (or if a get on the property is - performed using a N-API call). + performed using a N-API call). [`napi_callback`][] provides more details. * `setter`: A function to call when a set access of the property is performed. If this is passed in, set `value` and `method` to `NULL` (since these members won't be used). The given function is called implicitly by the runtime when the property is set from JavaScript code (or if a set on the property is - performed using a N-API call). + performed using a N-API call). [`napi_callback`][] provides more details. * `method`: Set this to make the property descriptor object's `value` property to be a JavaScript function represented by `method`. If this is passed in, set `value`, `getter` and `setter` to `NULL` (since these members - won't be used). + won't be used). [`napi_callback`][] provides more details. * `attributes`: The attributes associated with the particular property. See [`napi_property_attributes`][]. * `data`: The callback data passed into `method`, `getter` and `setter` if this diff --git a/n-api/napi_ref.md b/n-api/napi_ref.md index 1d620ccc..ffb9ad9e 100644 --- a/n-api/napi_ref.md +++ b/n-api/napi_ref.md @@ -6,5 +6,5 @@ This is the abstraction to use to reference a `napi_value`. This allows for users to manage the lifetimes of JavaScript values, including defining their minimum lifetimes explicitly. -For more details, review the [Object Lifetime Management][]. +For more details, review the [Object lifetime management][]. diff --git a/n-api/napi_set_instance_data.md b/n-api/napi_set_instance_data.md index 28da6815..8dffe0f0 100644 --- a/n-api/napi_set_instance_data.md +++ b/n-api/napi_set_instance_data.md @@ -16,6 +16,7 @@ napi_status napi_set_instance_data(napi_env env, * `[in] data`: The data item to make available to bindings of this instance. * `[in] finalize_cb`: The function to call when the environment is being torn down. The function receives `data` so that it might free it. + [`napi_finalize`][] provides more details. * `[in] finalize_hint`: Optional hint to pass to the finalize callback during collection. diff --git a/n-api/napi_threadsafe_function_call_js.md b/n-api/napi_threadsafe_function_call_js.md index 1926dd9b..84220ab1 100644 --- a/n-api/napi_threadsafe_function_call_js.md +++ b/n-api/napi_threadsafe_function_call_js.md @@ -40,3 +40,6 @@ typedef void (*napi_threadsafe_function_call_js)(napi_env env, This pointer is managed entirely by the threads and this callback. Thus this callback should free the data. +Unless for reasons discussed in [Object Lifetime Management][], creating a +handle and/or callback scope inside the function body is not necessary. + diff --git a/n-api/napi_unref_threadsafe_function.md b/n-api/napi_unref_threadsafe_function.md index cbd873dc..182816f5 100644 --- a/n-api/napi_unref_threadsafe_function.md +++ b/n-api/napi_unref_threadsafe_function.md @@ -122,6 +122,10 @@ This API may only be called from the main thread. + + + + diff --git a/n-api/napi_wrap.md b/n-api/napi_wrap.md index d3db50ae..4c1a814f 100644 --- a/n-api/napi_wrap.md +++ b/n-api/napi_wrap.md @@ -19,6 +19,7 @@ napi_status napi_wrap(napi_env env, JavaScript object. * `[in] finalize_cb`: Optional native callback that can be used to free the native instance when the JavaScript object is ready for garbage-collection. + [`napi_finalize`][] provides more details. * `[in] finalize_hint`: Optional contextual hint that is passed to the finalize callback. * `[out] result`: Optional reference to the wrapped object. diff --git a/n-api/prebuildify.md b/n-api/prebuildify.md index 02413aaa..26e0f18a 100644 --- a/n-api/prebuildify.md +++ b/n-api/prebuildify.md @@ -1,5 +1,5 @@ -[prebuildify][] is tool based on node-gyp. The advantage of prebuildify is +[prebuildify][] is a tool based on node-gyp. The advantage of prebuildify is that the built binaries are bundled with the native module when it's uploaded to npm. The binaries are downloaded from npm and are immediately available to the module user when the native module is installed. diff --git a/n-api/usage.md b/n-api/usage.md index 5e259675..84fbbed1 100644 --- a/n-api/usage.md +++ b/n-api/usage.md @@ -18,8 +18,7 @@ can be specified explicitly when including the header: This restricts the N-API surface to just the functionality that was available in the specified (and earlier) versions. -Some of the N-API surface is considered experimental and requires explicit -opt-in to access those APIs: +Some of the N-API surface is experimental and requires explicit opt-in: ```c #define NAPI_EXPERIMENTAL diff --git a/net/net.md b/net/net.md index fdbaff74..3a75af70 100644 --- a/net/net.md +++ b/net/net.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `net` 模块用于创建基于流的 TCP 或 [IPC] 的服务器([`net.createServer()`])与客户端([`net.createConnection()`])。 使用方法如下: diff --git a/net/socket_buffersize.md b/net/socket_buffersize.md index d2fc5a39..46985d5f 100644 --- a/net/socket_buffersize.md +++ b/net/socket_buffersize.md @@ -1,7 +1,11 @@ +> Stability: 0 - Deprecated: Use [`writable.writableLength`][] instead. + * {integer} 此属性显示为写入而缓冲的字符数。 diff --git a/os/os.md b/os/os.md index cbcd9a0b..f1e0aaad 100644 --- a/os/os.md +++ b/os/os.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `os` 模块提供了与操作系统相关的实用方法和属性。 使用方法如下: diff --git a/path/path.md b/path/path.md index f97a92ea..f7969bc0 100644 --- a/path/path.md +++ b/path/path.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `path` 模块提供了一些实用工具,用于处理文件和目录的路径。 可以使用以下方式访问它: diff --git a/perf_hooks/performance_measurement_apis.md b/perf_hooks/performance_measurement_apis.md index de723252..f85257bc 100644 --- a/perf_hooks/performance_measurement_apis.md +++ b/perf_hooks/performance_measurement_apis.md @@ -3,6 +3,8 @@ > Stability: 2 - Stable + + This module provides an implementation of a subset of the W3C [Web Performance APIs][] as well as additional APIs for Node.js-specific performance measurements. diff --git a/process/event_message.md b/process/event_message.md index c54718d8..00a31a1d 100644 --- a/process/event_message.md +++ b/process/event_message.md @@ -11,6 +11,6 @@ added: v0.5.10 生成的消息可能与最初发送的消息不同。 如果在衍生进程时使用了 `serialization` 选项设置为 `'advanced'`,则 `message` 参数可以包含 JSON 无法表示的数据。 -有关更多详细信息,请参见 [`child_process` 的高级序列化][Advanced Serialization]。 +有关更多详细信息,请参见 [`child_process` 的高级序列化][Advanced serialization for `child_process`]。 diff --git a/process/process.md b/process/process.md index 643ff67f..16226729 100644 --- a/process/process.md +++ b/process/process.md @@ -2,6 +2,8 @@ + + `process` 对象是一个全局变量,提供了有关当前 Node.js 进程的信息并对其进行控制。 作为全局变量,它始终可供 Node.js 应用程序使用,无需使用 `require()`。 它也可以使用 `require()` 显式地访问: diff --git a/process/process_report.md b/process/process_report.md index 0415bde3..675c3537 100644 --- a/process/process_report.md +++ b/process/process_report.md @@ -3,7 +3,7 @@ added: v11.8.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This API is no longer considered experimental. + description: This API is no longer experimental. --> * {Object} diff --git a/process/process_report_directory.md b/process/process_report_directory.md index ff338343..5e7aeec2 100644 --- a/process/process_report_directory.md +++ b/process/process_report_directory.md @@ -3,7 +3,7 @@ added: v11.12.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This API is no longer considered experimental. + description: This API is no longer experimental. --> * {string} diff --git a/process/process_report_filename.md b/process/process_report_filename.md index 5ca0d3bc..fdeb1d20 100644 --- a/process/process_report_filename.md +++ b/process/process_report_filename.md @@ -3,7 +3,7 @@ added: v11.12.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This API is no longer considered experimental. + description: This API is no longer experimental. --> * {string} diff --git a/process/process_report_getreport_err.md b/process/process_report_getreport_err.md index c176c927..e72fc0ca 100644 --- a/process/process_report_getreport_err.md +++ b/process/process_report_getreport_err.md @@ -3,7 +3,7 @@ added: v11.8.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This API is no longer considered experimental. + description: This API is no longer experimental. --> * `err` {Error} A custom error used for reporting the JavaScript stack. diff --git a/process/process_report_reportonsignal.md b/process/process_report_reportonsignal.md index de743f7a..c7267c2d 100644 --- a/process/process_report_reportonsignal.md +++ b/process/process_report_reportonsignal.md @@ -3,7 +3,7 @@ added: v11.12.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This API is no longer considered experimental. + description: This API is no longer experimental. --> * {boolean} diff --git a/process/process_report_reportonuncaughtexception.md b/process/process_report_reportonuncaughtexception.md index e651c7dc..89b070d4 100644 --- a/process/process_report_reportonuncaughtexception.md +++ b/process/process_report_reportonuncaughtexception.md @@ -3,7 +3,7 @@ added: v11.12.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This API is no longer considered experimental. + description: This API is no longer experimental. --> * {boolean} diff --git a/process/process_report_signal.md b/process/process_report_signal.md index c92e6ce2..30cbfd5e 100644 --- a/process/process_report_signal.md +++ b/process/process_report_signal.md @@ -3,7 +3,7 @@ added: v11.12.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This API is no longer considered experimental. + description: This API is no longer experimental. --> * {string} diff --git a/process/process_report_writereport_filename_err.md b/process/process_report_writereport_filename_err.md index b9aa5600..a232be5b 100644 --- a/process/process_report_writereport_filename_err.md +++ b/process/process_report_writereport_filename_err.md @@ -3,7 +3,7 @@ added: v11.8.0 changes: - version: v13.12.0 pr-url: https://github.com/nodejs/node/pull/32242 - description: This API is no longer considered experimental. + description: This API is no longer experimental. --> * `filename` {string} Name of the file where the report is written. This diff --git a/process/process_stdin.md b/process/process_stdin.md index c6701842..41309171 100644 --- a/process/process_stdin.md +++ b/process/process_stdin.md @@ -4,21 +4,7 @@ `process.stdin` 属性返回连接到 `stdin` (fd `0`) 的流。 它是一个 [`net.Socket`] 流(也就是[双工流][Duplex]),除非 fd `0` 指向一个文件,在这种情况下它是一个[可读流][Readable]。 -```js -process.stdin.setEncoding('utf8'); - -process.stdin.on('readable', () => { - let chunk; - // 使用循环确保我们读取所有的可用数据。 - while ((chunk = process.stdin.read()) !== null) { - process.stdout.write(`数据: ${chunk}`); - } -}); - -process.stdin.on('end', () => { - process.stdout.write('结束'); -}); -``` +有关如何从 `stdin` 中读取的详细信息,参见 [`readable.read()`]。 作为[双工流][Duplex],`process.stdin` 也可以在“旧”模式下使用,该模式与在 v0.10 之前为 Node.js 编写的脚本兼容。 有关更多信息,参见[流的兼容性][Stream compatibility]。 diff --git a/punycode/punycode.md b/punycode/punycode.md index d02ea0f0..654e6e1b 100644 --- a/punycode/punycode.md +++ b/punycode/punycode.md @@ -9,6 +9,8 @@ changes: > Stability: 0 - Deprecated + + **The version of the punycode module bundled in Node.js is being deprecated**. In a future major version of Node.js this module will be removed. Users currently depending on the `punycode` module should switch to using the diff --git a/querystring/query_string.md b/querystring/query_string.md index 4867599d..8a526bbc 100644 --- a/querystring/query_string.md +++ b/querystring/query_string.md @@ -5,6 +5,8 @@ + + `querystring` 模块提供用于解析和格式化 URL 查询字符串的实用工具。 可以使用以下方式访问它: diff --git a/readline/readline.md b/readline/readline.md index 4c5f05a5..f8991e52 100644 --- a/readline/readline.md +++ b/readline/readline.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `readline` 模块提供了一个接口,用于一次一行地读取[可读流][Readable](例如 [`process.stdin`])中的数据。 可以使用以下方式访问它: diff --git a/repl/repl.md b/repl/repl.md index ed4ccadd..2c687509 100644 --- a/repl/repl.md +++ b/repl/repl.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `repl` 模块提供了一种“读取-求值-输出”循环(REPL)的实现,它可作为一个独立的程序或嵌入到其他应用中。 可以通过以下方式使用它: diff --git a/stream/api_for_stream_consumers.md b/stream/api_for_stream_consumers.md index e04db65c..5574a223 100644 --- a/stream/api_for_stream_consumers.md +++ b/stream/api_for_stream_consumers.md @@ -57,4 +57,4 @@ server.listen(1337); 对于只需写入数据到流或从流消费数据的应用程序,并不需要直接实现流的接口,通常也不需要调用 `require('stream')`。 -对于需要实现新类型的流的开发者,可以参见[用于实现流的API][API for Stream Implementers]章节。 +对于需要实现新类型的流的开发者,可以参见[用于实现流的API][API for stream implementers]章节。 diff --git a/stream/readable_read_size.md b/stream/readable_read_size.md index ee14bfef..dfb49064 100644 --- a/stream/readable_read_size.md +++ b/stream/readable_read_size.md @@ -21,12 +21,47 @@ added: v0.9.4 ```js const readable = getReadableStreamSomehow(); + +// 'readable' may be triggered multiple times as data is buffered in +readable.on('readable', () => { + let chunk; + console.log('Stream is readable (new data received in buffer)'); + // Use a loop to make sure we read all currently available data + while (null !== (chunk = readable.read())) { + console.log(`读取 ${chunk.length} 字节的数据`); + } +}); + +// 'end' will be triggered once when there is no more data available +readable.on('end', () => { + console.log('Reached end of stream.'); +}); +``` + +Each call to `readable.read()` returns a chunk of data, or `null`. The chunks +are not concatenated. A `while` loop is necessary to consume all data +currently in the buffer. When reading a large file `.read()` may return `null`, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new `'readable'` event will be emitted +when there is more data in the buffer. Finally the `'end'` event will be +emitted when there is no more data to come. + +Therefore to read a file's whole contents from a `readable`, it is necessary +to collect chunks across multiple `'readable'` events: + +```js +const chunks = []; + readable.on('readable', () => { let chunk; while (null !== (chunk = readable.read())) { - console.log(`接收到 ${chunk.length} 字节的数据`); + chunks.push(chunk); } }); + +readable.on('end', () => { + const content = chunks.join(''); +}); ``` 使用 `readable.read()` 处理数据时,`while` 循环是必需的。 diff --git a/stream/readable_readableflowing.md b/stream/readable_readableflowing.md index f1a819a6..ea74bd65 100644 --- a/stream/readable_readableflowing.md +++ b/stream/readable_readableflowing.md @@ -5,5 +5,5 @@ added: v9.4.0 * {boolean} This property reflects the current state of a `Readable` stream as described -in the [Stream Three States][] section. +in the [Three states][] section. diff --git a/stream/readable_unshift_chunk_encoding.md b/stream/readable_unshift_chunk_encoding.md index e4a8d77e..78716adf 100644 --- a/stream/readable_unshift_chunk_encoding.md +++ b/stream/readable_unshift_chunk_encoding.md @@ -20,7 +20,7 @@ EOF 信号会被放在 buffer 的末尾,任何缓冲的数据仍将会被刷 触发 [`'end'`] 事件或抛出运行时错误之后,不能再调用 `stream.unshift()` 方法。 使用 `stream.unshift()` 的开发者可以考虑切换到 [`Transform`] 流。 -详见[用于实现流的API][API for Stream Implementers]。 +详见[用于实现流的API][API for stream implementers]。 ```js // 拉出由 \n\n 分隔的标题。 diff --git a/stream/stream.md b/stream/stream.md index 922077a3..b2ad687d 100644 --- a/stream/stream.md +++ b/stream/stream.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + 流(stream)是 Node.js 中处理流式数据的抽象接口。 `stream` 模块用于构建实现了流接口的对象。 diff --git a/stream/stream_pipeline_source_transforms_destination_callback.md b/stream/stream_pipeline_source_transforms_destination_callback.md index 2a916d04..e69de29b 100644 --- a/stream/stream_pipeline_source_transforms_destination_callback.md +++ b/stream/stream_pipeline_source_transforms_destination_callback.md @@ -1,99 +0,0 @@ - - -* `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'); -const fs = require('fs'); -const zlib = require('zlib'); - -// 使用 pipeline API 轻松地将一系列的流通过管道一起传送,并在管道完全地完成时获得通知。 - -// 使用 pipeline 可以有效地压缩一个可能很大的 tar 文件: - -pipeline( - fs.createReadStream('archive.tar'), - zlib.createGzip(), - fs.createWriteStream('archive.tar.gz'), - (err) => { - if (err) { - console.error('管道传送失败', err); - } else { - console.log('管道传送成功'); - } - } -); -``` - -`pipeline` API 也可以 promise 化: - -```js -const pipeline = util.promisify(stream.pipeline); - -async function run() { - await pipeline( - fs.createReadStream('archive.tar'), - zlib.createGzip(), - fs.createWriteStream('archive.tar.gz') - ); - console.log('管道传送成功'); -} - -run().catch(console.error); -``` - -`pipeline` API 还支持异步的生成器: - -```js -const pipeline = util.promisify(stream.pipeline); -const fs = require('fs'); - -async function run() { - await pipeline( - fs.createReadStream('lowercase.txt'), - async function* (source) { - source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. - for await (const chunk of source) { - yield chunk.toUpperCase(); - } - }, - fs.createWriteStream('uppercase.txt') - ); - console.log('Pipeline 成功'); -} - -run().catch(console.error); -``` - -`stream.pipeline()` 将会在所有的流上调用 `stream.destroy(err)`,除了: -* 已触发 `'end'` 或 `'close'` 的 `Readable` 流。 -* 已触发 `'finish'` 或 `'close'` 的 `Writable` 流。 - -在调用 `callback` 之后,`stream.pipeline()` 会将悬挂的事件监听器留在流上。 -在失败后重新使用流的情况下,这可能导致事件监听器泄漏和误吞的错误。 - diff --git a/stream/stream_pipeline_streams_callback.md b/stream/stream_pipeline_streams_callback.md new file mode 100644 index 00000000..abc9e0c0 --- /dev/null +++ b/stream/stream_pipeline_streams_callback.md @@ -0,0 +1,100 @@ + + +* `streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]} +* `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'); +const fs = require('fs'); +const zlib = require('zlib'); + +// 使用 pipeline API 轻松地将一系列的流通过管道一起传送,并在管道完全地完成时获得通知。 + +// 使用 pipeline 可以有效地压缩一个可能很大的 tar 文件: + +pipeline( + fs.createReadStream('archive.tar'), + zlib.createGzip(), + fs.createWriteStream('archive.tar.gz'), + (err) => { + if (err) { + console.error('管道传送失败', err); + } else { + console.log('管道传送成功'); + } + } +); +``` + +`pipeline` API 也可以 promise 化: + +```js +const pipeline = util.promisify(stream.pipeline); + +async function run() { + await pipeline( + fs.createReadStream('archive.tar'), + zlib.createGzip(), + fs.createWriteStream('archive.tar.gz') + ); + console.log('管道传送成功'); +} + +run().catch(console.error); +``` + +`pipeline` API 还支持异步的生成器: + +```js +const pipeline = util.promisify(stream.pipeline); +const fs = require('fs'); + +async function run() { + await pipeline( + fs.createReadStream('lowercase.txt'), + async function* (source) { + source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + for await (const chunk of source) { + yield chunk.toUpperCase(); + } + }, + fs.createWriteStream('uppercase.txt') + ); + console.log('Pipeline 成功'); +} + +run().catch(console.error); +``` + +`stream.pipeline()` 将会在所有的流上调用 `stream.destroy(err)`,除了: +* 已触发 `'end'` 或 `'close'` 的 `Readable` 流。 +* 已触发 `'finish'` 或 `'close'` 的 `Writable` 流。 + +在调用 `callback` 之后,`stream.pipeline()` 会将悬挂的事件监听器留在流上。 +在失败后重新使用流的情况下,这可能导致事件监听器泄漏和误吞的错误。 + diff --git a/stream/transform_flush_callback.md b/stream/transform_flush_callback.md index 8d5709f0..82ca80f9 100644 --- a/stream/transform_flush_callback.md +++ b/stream/transform_flush_callback.md @@ -12,7 +12,7 @@ 自定义的[转换流]的 `transform._flush()` 方法是可选的。 当没有更多数据要被消费时,就会调用这个方法,但如果是在 [`'end'`] 事件被触发之前调用则会发出可读流结束的信号。 -在 `transform._flush()` 的实现中,`readable.push()` 可能会被调用零次或多次。 +在 `transform._flush()` 的实现中,`transform.push()` 可能会被调用零次或多次。 当 flush 操作完成时,必须调用 `callback` 函数。 `transform._flush()` 方法有下划线前缀,因为它是在定义在类的内部,不应该被用户程序直接调用。 diff --git a/stream/transform_transform_chunk_encoding_callback.md b/stream/transform_transform_chunk_encoding_callback.md index 4e9feb4b..9a0b6574 100644 --- a/stream/transform_transform_chunk_encoding_callback.md +++ b/stream/transform_transform_chunk_encoding_callback.md @@ -10,7 +10,7 @@ 所有转换流的实现都必须提供 `_transform()` 方法来接收输入并生产输出。 -`transform._transform()` 的实现会处理写入的字节,进行一些计算操作,然后使用 `readable.push()` 输出到可读流。 +`transform._transform()` 的实现会处理写入的字节,进行一些计算操作,然后使用 `transform.push()` 输出到可读流。 `transform.push()` 可能会被调用零次或多次用来从每次输入的数据块产生输出,调用的次数取决需要多少数据来产生输出的结果。 @@ -18,7 +18,7 @@ 当前数据被完全消费之后,必须调用 `callback` 函数。 当处理输入的过程中发生出错时,`callback` 的第一个参数传入 `Error` 对象,否则传入 `null`。 -如果 `callback` 传入了第二个参数,则它会被转发到 `readable.push()`。 +如果 `callback` 传入了第二个参数,则它会被转发到 `transform.push()`。 就像下面的例子: ```js diff --git a/string_decoder/string_decoder.md b/string_decoder/string_decoder.md index 4a6846c5..3b89d2b7 100644 --- a/string_decoder/string_decoder.md +++ b/string_decoder/string_decoder.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `string_decoder` 模块提供了一个 API,用一种能保护已编码的多字节 UTF-8 和 UTF-16 字符的方式将 `Buffer` 对象解码为字符串。 可以使用以下方式访问它: diff --git a/synopsis/usage_example.md b/synopsis/usage_and_example.md similarity index 100% rename from synopsis/usage_example.md rename to synopsis/usage_and_example.md diff --git a/timers/timers.md b/timers/timers.md index 22e09927..b6206876 100644 --- a/timers/timers.md +++ b/timers/timers.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `timer` 模块开放了一个全局的 API,用于安排函数在未来某个时间点被调用。 因为定时器函数是全局的,所以使用 API 不需要调用 `require('timers')`。 diff --git a/tls/perfect_forward_secrecy.md b/tls/perfect_forward_secrecy.md index 4c14fea4..7061fb1b 100644 --- a/tls/perfect_forward_secrecy.md +++ b/tls/perfect_forward_secrecy.md @@ -1,7 +1,7 @@ -术语“[前向保密][Forward Secrecy]”或“完全前向保密”是一种密钥协商(或称做密钥交换)方法。 +术语“[前向保密][forward secrecy]”或“完全前向保密”是一种密钥协商(或称做密钥交换)方法。 通过这种方法,客户端与服务端在当前会话中,协商一个临时生成的密钥进行对称加密的密钥交换。 这意味着即使服务器端私钥发生泄漏,窃密者与攻击者也无法解密通信内容,除非他们能得到当前会话的临时密钥。 diff --git a/tls/session_identifiers.md b/tls/session_identifiers.md new file mode 100644 index 00000000..2c627193 --- /dev/null +++ b/tls/session_identifiers.md @@ -0,0 +1,20 @@ + +Servers generate a unique ID for new connections and +send it to the client. Clients and servers save the session state. When +reconnecting, clients send the ID of their saved session state and if the server +also has the state for that ID, it can agree to use it. Otherwise, the server +will create a new session. See [RFC 2246][] for more information, page 23 and +30. + +Resumption using session identifiers is supported by most web browsers when +making HTTPS requests. + +For Node.js, clients wait for the [`'session'`][] event to get the session data, +and provide the data to the `session` option of a subsequent [`tls.connect()`][] +to reuse the session. Servers must +implement handlers for the [`'newSession'`][] and [`'resumeSession'`][] events +to save and restore the session data using the session ID as the lookup key to +reuse sessions. To reuse sessions across load balancers or cluster workers, +servers must use a shared session cache (such as Redis) in their session +handlers. + diff --git a/tls/session_resumption.md b/tls/session_resumption.md index 497f95bf..0d642920 100644 --- a/tls/session_resumption.md +++ b/tls/session_resumption.md @@ -3,89 +3,3 @@ Establishing a TLS session can be relatively slow. The process can be sped up by saving and later reusing the session state. There are several mechanisms to do so, discussed here from oldest to newest (and preferred). -***Session Identifiers*** Servers generate a unique ID for new connections and -send it to the client. Clients and servers save the session state. When -reconnecting, clients send the ID of their saved session state and if the server -also has the state for that ID, it can agree to use it. Otherwise, the server -will create a new session. See [RFC 2246][] for more information, page 23 and -30. - -Resumption using session identifiers is supported by most web browsers when -making HTTPS requests. - -For Node.js, clients wait for the [`'session'`][] event to get the session data, -and provide the data to the `session` option of a subsequent [`tls.connect()`][] -to reuse the session. Servers must -implement handlers for the [`'newSession'`][] and [`'resumeSession'`][] events -to save and restore the session data using the session ID as the lookup key to -reuse sessions. To reuse sessions across load balancers or cluster workers, -servers must use a shared session cache (such as Redis) in their session -handlers. - -***Session Tickets*** The servers encrypt the entire session state and send it -to the client as a "ticket". When reconnecting, the state is sent to the server -in the initial connection. This mechanism avoids the need for server-side -session cache. If the server doesn't use the ticket, for any reason (failure -to decrypt it, it's too old, etc.), it will create a new session and send a new -ticket. See [RFC 5077][] for more information. - -Resumption using session tickets is becoming commonly supported by many web -browsers when making HTTPS requests. - -For Node.js, clients use the same APIs for resumption with session identifiers -as for resumption with session tickets. For debugging, if -[`tls.TLSSocket.getTLSTicket()`][] returns a value, the session data contains a -ticket, otherwise it contains client-side session state. - -With TLSv1.3, be aware that multiple tickets may be sent by the server, -resulting in multiple `'session'` events, see [`'session'`][] for more -information. - -Single process servers need no specific implementation to use session tickets. -To use session tickets across server restarts or load balancers, servers must -all have the same ticket keys. There are three 16-byte keys internally, but the -tls API exposes them as a single 48-byte buffer for convenience. - -Its possible to get the ticket keys by calling [`server.getTicketKeys()`][] on -one server instance and then distribute them, but it is more reasonable to -securely generate 48 bytes of secure random data and set them with the -`ticketKeys` option of [`tls.createServer()`][]. The keys should be regularly -regenerated and server's keys can be reset with -[`server.setTicketKeys()`][]. - -Session ticket keys are cryptographic keys, and they ***must be stored -securely***. With TLS 1.2 and below, if they are compromised all sessions that -used tickets encrypted with them can be decrypted. They should not be stored -on disk, and they should be regenerated regularly. - -If clients advertise support for tickets, the server will send them. The -server can disable tickets by supplying -`require('constants').SSL_OP_NO_TICKET` in `secureOptions`. - -Both session identifiers and session tickets timeout, causing the server to -create new sessions. The timeout can be configured with the `sessionTimeout` -option of [`tls.createServer()`][]. - -For all the mechanisms, when resumption fails, servers will create new sessions. -Since failing to resume the session does not cause TLS/HTTPS connection -failures, it is easy to not notice unnecessarily poor TLS performance. The -OpenSSL CLI can be used to verify that servers are resuming sessions. Use the -`-reconnect` option to `openssl s_client`, for example: - -```console -$ openssl s_client -connect localhost:443 -reconnect -``` - -Read through the debug output. The first connection should say "New", for -example: - -```text -New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256 -``` - -Subsequent connections should say "Reused", for example: - -```text -Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256 -``` - diff --git a/tls/session_tickets.md b/tls/session_tickets.md new file mode 100644 index 00000000..39d5e875 --- /dev/null +++ b/tls/session_tickets.md @@ -0,0 +1,68 @@ + +The servers encrypt the entire session state and send it +to the client as a "ticket". When reconnecting, the state is sent to the server +in the initial connection. This mechanism avoids the need for server-side +session cache. If the server doesn't use the ticket, for any reason (failure +to decrypt it, it's too old, etc.), it will create a new session and send a new +ticket. See [RFC 5077][] for more information. + +Resumption using session tickets is becoming commonly supported by many web +browsers when making HTTPS requests. + +For Node.js, clients use the same APIs for resumption with session identifiers +as for resumption with session tickets. For debugging, if +[`tls.TLSSocket.getTLSTicket()`][] returns a value, the session data contains a +ticket, otherwise it contains client-side session state. + +With TLSv1.3, be aware that multiple tickets may be sent by the server, +resulting in multiple `'session'` events, see [`'session'`][] for more +information. + +Single process servers need no specific implementation to use session tickets. +To use session tickets across server restarts or load balancers, servers must +all have the same ticket keys. There are three 16-byte keys internally, but the +tls API exposes them as a single 48-byte buffer for convenience. + +Its possible to get the ticket keys by calling [`server.getTicketKeys()`][] on +one server instance and then distribute them, but it is more reasonable to +securely generate 48 bytes of secure random data and set them with the +`ticketKeys` option of [`tls.createServer()`][]. The keys should be regularly +regenerated and server's keys can be reset with +[`server.setTicketKeys()`][]. + +Session ticket keys are cryptographic keys, and they ***must be stored +securely***. With TLS 1.2 and below, if they are compromised all sessions that +used tickets encrypted with them can be decrypted. They should not be stored +on disk, and they should be regenerated regularly. + +If clients advertise support for tickets, the server will send them. The +server can disable tickets by supplying +`require('constants').SSL_OP_NO_TICKET` in `secureOptions`. + +Both session identifiers and session tickets timeout, causing the server to +create new sessions. The timeout can be configured with the `sessionTimeout` +option of [`tls.createServer()`][]. + +For all the mechanisms, when resumption fails, servers will create new sessions. +Since failing to resume the session does not cause TLS/HTTPS connection +failures, it is easy to not notice unnecessarily poor TLS performance. The +OpenSSL CLI can be used to verify that servers are resuming sessions. Use the +`-reconnect` option to `openssl s_client`, for example: + +```console +$ openssl s_client -connect localhost:443 -reconnect +``` + +Read through the debug output. The first connection should say "New", for +example: + +```text +New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256 +``` + +Subsequent connections should say "Reused", for example: + +```text +Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256 +``` + diff --git a/tls/tls_createsecurecontext_options.md b/tls/tls_createsecurecontext_options.md index a36bdd91..b4320868 100644 --- a/tls/tls_createsecurecontext_options.md +++ b/tls/tls_createsecurecontext_options.md @@ -86,7 +86,7 @@ changes: * `crl` {string|string[]|Buffer|Buffer[]} PEM formatted CRLs (Certificate Revocation Lists). * `dhparam` {string|Buffer} Diffie Hellman parameters, required for - [Perfect Forward Secrecy][]. Use `openssl dhparam` to create the parameters. + [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits or else an error will be thrown. Although 1024 bits is permissible, use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently @@ -153,6 +153,11 @@ changes: **Default:** none, see `minVersion`. * `sessionIdContext` {string} Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients. + * `ticketKeys`: {Buffer} 48-bytes of cryptographically strong pseudo-random + data. See [Session Resumption][] for more information. + * `sessionTimeout` {number} The number of seconds after which a TLS session + created by the server will no longer be resumable. See + [Session Resumption][] for more information. **Default:** `300`. [`tls.createServer()`][] sets the default value of the `honorCipherOrder` option to `true`, other APIs that create secure contexts leave it unset. diff --git a/tls/tls_createserver_options_secureconnectionlistener.md b/tls/tls_createserver_options_secureconnectionlistener.md index c853f69e..4f050da1 100644 --- a/tls/tls_createserver_options_secureconnectionlistener.md +++ b/tls/tls_createserver_options_secureconnectionlistener.md @@ -45,12 +45,15 @@ changes: * `sessionTimeout` {number} The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information. **Default:** `300`. - * `SNICallback(servername, cb)` {Function} A function that will be called if - the client supports SNI TLS extension. Two arguments will be passed when - called: `servername` and `cb`. `SNICallback` should invoke `cb(null, ctx)`, - where `ctx` is a `SecureContext` instance. (`tls.createSecureContext(...)` - can be used to get a proper `SecureContext`.) If `SNICallback` wasn't - provided the default callback with high-level API will be used (see below). + * `SNICallback(servername, callback)` {Function} A function that will be + called if the client supports SNI TLS extension. Two arguments will be + passed when called: `servername` and `callback`. `callback` is an + error-first callback that takes two optional arguments: `error` and `ctx`. + `ctx`, if provided, is a `SecureContext` instance. + [`tls.createSecureContext()`][] can be used to get a proper `SecureContext`. + If `callback` is called with a falsy `ctx` argument, the default secure + context of the server will be used. If `SNICallback` wasn't provided the + default callback with high-level API will be used (see below). * `ticketKeys`: {Buffer} 48-bytes of cryptographically strong pseudo-random data. See [Session Resumption][] for more information. * `pskCallback` {Function} diff --git a/tls/tls_ssl.md b/tls/tls_ssl.md index bf573eab..ae035a36 100644 --- a/tls/tls_ssl.md +++ b/tls/tls_ssl.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `tls` 模块是对安全传输层(TLS)及安全套接层(SSL)协议的实现,建立在OpenSSL的基础上。 按如下方式引用此模块: diff --git a/tls/tlssocket_getephemeralkeyinfo.md b/tls/tlssocket_getephemeralkeyinfo.md index 79c6824c..7071e04c 100644 --- a/tls/tlssocket_getephemeralkeyinfo.md +++ b/tls/tlssocket_getephemeralkeyinfo.md @@ -5,7 +5,7 @@ added: v5.0.0 * Returns: {Object} Returns an object representing the type, name, and size of parameter of -an ephemeral key exchange in [Perfect Forward Secrecy][] on a client +an ephemeral key exchange in [perfect forward secrecy][] on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; `null` is returned if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The diff --git a/tracing/trace_events.md b/tracing/trace_events.md index ff958faa..a9e71945 100644 --- a/tracing/trace_events.md +++ b/tracing/trace_events.md @@ -3,8 +3,10 @@ > Stability: 1 - Experimental -Trace Event provides a mechanism to centralize tracing information generated by -V8, Node.js core, and userspace code. + + +The `trace_events` module provides a mechanism to centralize tracing information +generated by V8, Node.js core, and userspace code. Tracing can be enabled with the `--trace-event-categories` command-line flag or by using the `trace_events` module. The `--trace-event-categories` flag diff --git a/tty/tty.md b/tty/tty.md index 9d19648a..231640da 100644 --- a/tty/tty.md +++ b/tty/tty.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `tty` 模块提供了 `tty.ReadStream` 和 `tty.WriteStream` 类。 在大多数情况下,不需要也不可能直接地使用此模块。 但是,可以使用以下方法访问它: diff --git a/url/url.md b/url/url.md index 67f5f896..b2cb705c 100644 --- a/url/url.md +++ b/url/url.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `url` 模块用于处理与解析 URL。 使用方法如下: diff --git a/url/url_parse_urlstring_parsequerystring_slashesdenotehost.md b/url/url_parse_urlstring_parsequerystring_slashesdenotehost.md index 66f17da0..7750cbdf 100644 --- a/url/url_parse_urlstring_parsequerystring_slashesdenotehost.md +++ b/url/url_parse_urlstring_parsequerystring_slashesdenotehost.md @@ -33,3 +33,9 @@ A `TypeError` is thrown if `urlString` is not a string. A `URIError` is thrown if the `auth` property is present but cannot be decoded. +Use of the legacy `url.parse()` method is discouraged. Users should +use the WHATWG `URL` API. Because the `url.parse()` method uses a +lenient, non-standard algorithm for parsing URL strings, security +issues can be introduced. Specifically, issues with [host name spoofing][] and +incorrect handling of usernames and passwords have been identified. + diff --git a/util/util.md b/util/util.md index e9f1d048..03021aa3 100644 --- a/util/util.md +++ b/util/util.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `util` 模块用于支持 Node.js 内部 API 的需求。 大部分实用工具也可用于应用程序与模块开发者。 使用方法如下: diff --git a/util/util_debuglog_section.md b/util/util_debuglog_section_callback.md similarity index 69% rename from util/util_debuglog_section.md rename to util/util_debuglog_section_callback.md index af5e7e8a..9f7dc080 100644 --- a/util/util_debuglog_section.md +++ b/util/util_debuglog_section_callback.md @@ -3,6 +3,8 @@ added: v0.11.3 --> * `section` {string} 一个字符串,指定要为应用的哪些部分创建 `debuglog` 函数。 +* `callback` {Function} A callback invoked the first time the logging function +is called with a function argument that is a more optimized logging function. * 返回: {Function} 日志函数。 `util.debuglog()` 方法用于创建一个函数,基于 `NODE_DEBUG` 环境变量的存在与否有条件地写入调试信息到 `stderr`。 @@ -43,3 +45,18 @@ FOO-BAR 3257: hi there, it's foo-bar [2333] `NODE_DEBUG` 环境变量中可指定多个由逗号分隔的 `section` 名称。 例如:`NODE_DEBUG=fs,net,tls`。 +The optional `callback` argument can be used to replace the logging function +with a different function that doesn't have any initialization or +unnecessary wrapping. + +```js +const util = require('util'); +let debuglog = util.debuglog('internals', (debug) => { + // Replace with a logging function that optimizes out + // testing if the section is enabled + debuglog = debug; +}); +``` + + + diff --git a/util/util_inspect_object_showhidden_depth_colors.md b/util/util_inspect_object_showhidden_depth_colors.md index a8373ac2..b56369bd 100644 --- a/util/util_inspect_object_showhidden_depth_colors.md +++ b/util/util_inspect_object_showhidden_depth_colors.md @@ -2,6 +2,13 @@ added: v0.3.0 changes: - version: v14.0.0 + pr-url: https://github.com/nodejs/node/pull/33690 + description: If `object` is from a different `vm.Context` now, a custom + inspection function on it will not receive context-specific + arguments anymore. + - version: + - v13.13.0 + - v12.17.0 pr-url: https://github.com/nodejs/node/pull/32392 description: The `maxStringLength` option is supported now. - version: diff --git a/v8/v8.md b/v8/v8.md index 1fcd792a..8215a2a8 100644 --- a/v8/v8.md +++ b/v8/v8.md @@ -1,6 +1,8 @@ + + `v8` 模块暴露了特定于内置到 Node.js 二进制文件中的 [V8] 版本的 API。 可以使用以下方式访问它: diff --git a/v8/v8_writeheapsnapshot_filename.md b/v8/v8_writeheapsnapshot_filename.md index 385e5f0b..2668e277 100644 --- a/v8/v8_writeheapsnapshot_filename.md +++ b/v8/v8_writeheapsnapshot_filename.md @@ -12,7 +12,7 @@ added: v11.13.0 JSON 模式未记录且特定于V8引擎,并且可能从 V8 的一个版本更改为下一个版本。 堆快照特定于单个 V8 隔离。 -使用[工作线程][Worker Threads]时,从主线程生成的堆快照将不包含有关工作线程的任何信息,反之亦然。 +使用[工作线程][worker threads]时,从主线程生成的堆快照将不包含有关工作线程的任何信息,反之亦然。 ```js const { writeHeapSnapshot } = require('v8'); diff --git a/vm/script_runinnewcontext_contextobject_options.md b/vm/script_runinnewcontext_contextobject_options.md index a4010a78..9d57032b 100644 --- a/vm/script_runinnewcontext_contextobject_options.md +++ b/vm/script_runinnewcontext_contextobject_options.md @@ -1,6 +1,9 @@ + + `vm` 模块可在 V8 虚拟机上下文中编译和运行代码。 `vm` 模块不是安全的机制。 不要使用它来运行不受信任的代码。 diff --git a/vm/vm_runinnewcontext_code_contextobject_options.md b/vm/vm_runinnewcontext_code_contextobject_options.md index c2335215..4384d774 100644 --- a/vm/vm_runinnewcontext_code_contextobject_options.md +++ b/vm/vm_runinnewcontext_code_contextobject_options.md @@ -1,6 +1,9 @@ + +* `instance` {WebAssembly.Instance} + +Attempt to initialize `instance` as a WASI reactor by invoking its +`_initialize()` export, if it is present. If `instance` contains a `_start()` +export, then an exception is thrown. + +`initialize()` requires that `instance` exports a [`WebAssembly.Memory`][] named +`memory`. If `instance` does not have a `memory` export an exception is thrown. + +If `initialize()` is called more than once, an exception is thrown. + diff --git a/wasi/webassembly_system_interface_wasi.md b/wasi/webassembly_system_interface_wasi.md index 6d20ea81..742bfd3b 100644 --- a/wasi/webassembly_system_interface_wasi.md +++ b/wasi/webassembly_system_interface_wasi.md @@ -3,6 +3,8 @@ > Stability: 1 - Experimental + + The WASI API provides an implementation of the [WebAssembly System Interface][] specification. WASI gives sandboxed WebAssembly applications access to the underlying operating system via a collection of POSIX-like functions. diff --git a/worker_threads/new_worker_filename_options.md b/worker_threads/new_worker_filename_options.md index 58e7c98c..1367398b 100644 --- a/worker_threads/new_worker_filename_options.md +++ b/worker_threads/new_worker_filename_options.md @@ -1,6 +1,10 @@ + `worker_threads` 模块允许使用并行地执行 JavaScript 的线程。 要访问它: diff --git a/worker_threads/worker_unref.md b/worker_threads/worker_unref.md index d5ef39c1..c41c7f69 100644 --- a/worker_threads/worker_unref.md +++ b/worker_threads/worker_unref.md @@ -58,6 +58,8 @@ active handle in the event system. If the worker is already `unref()`ed calling + + diff --git a/zlib/compressing_http_requests_and_responses.md b/zlib/compressing_http_requests_and_responses.md index 157eacfa..1396c478 100644 --- a/zlib/compressing_http_requests_and_responses.md +++ b/zlib/compressing_http_requests_and_responses.md @@ -6,7 +6,7 @@ HTTP 的 [`Accept-Encoding`] 消息头用来标记客户端接受的压缩编码 下面给出的示例大幅简化,用以展示了基本的概念。 使用 `zlib` 编码成本会很高, 结果应该被缓存。 -关于 `zlib` 使用中有关速度/内存/压缩互相权衡的信息,查阅[内存使用的调整][Memory Usage Tuning]。 +关于 `zlib` 使用中有关速度/内存/压缩互相权衡的信息,查阅[内存使用的调整][Memory usage tuning]。 ```js // 客户端请求示例。 diff --git a/zlib/zlib.md b/zlib/zlib.md index fc122952..7bf2f6d8 100644 --- a/zlib/zlib.md +++ b/zlib/zlib.md @@ -3,6 +3,8 @@ > 稳定性: 2 - 稳定 + + `zlib` 模块提供通过 Gzip、Deflate/Inflate、和 Brotli 实现的压缩功能。 可以通过这样使用它:
Constant